/*
 *************************************************************************
 * The contents of this file are subject to the Openbravo  Public  License
 * Version  1.0  (the  "License"),  being   the  Mozilla   Public  License
 * Version 1.1  with a permitted attribution clause; you may not  use this
 * file except in compliance with the License. You  may  obtain  a copy of
 * the License at http://www.openbravo.com/legal/license.html 
 * Software distributed under the License  is  distributed  on  an "AS IS"
 * basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See the
 * License for the specific  language  governing  rights  and  limitations
 * under the License. 
 * The Original Code is Openbravo ERP. 
 * The Initial Developer of the Original Code is Openbravo SL 
 * All portions are Copyright (C) 2001-2006 Openbravo SL 
 * All Rights Reserved. 
 * Contributor(s):  ______________________________________.
 ************************************************************************
*/
package org.openbravo.wad;

import org.openbravo.data.Sqlc;
import org.openbravo.utils.FileUtility;
import org.openbravo.utils.DirFilter;
import org.openbravo.utils.FormatUtilities;
import org.openbravo.data.FieldProvider;

import org.openbravo.xmlEngine.XmlDocument;
import org.openbravo.xmlEngine.XmlEngine;

import org.openbravo.wad.controls.*;

import java.io.*;
import javax.servlet.*;

import java.util.Vector;
import java.util.Enumeration;
import java.util.Properties;

import org.xml.sax.helpers.DefaultHandler;

import org.apache.log4j.Logger;
import org.apache.log4j.PropertyConfigurator;

public class Wad extends DefaultHandler {
  static final int NUM_COLUMNS = 10;
  static final int COLUMN_1_OF_1 = 11;
  static final int COLUMN_1_OF_2 = 12;
  static final int COLUMN_2_OF_2 = 22;
  static final int NUM_TABS = 8;
  static final int INCR_TABS = 8;
  static final int HEIGHT_TABS = 38;
  static final int MAX_COL_SIZE_RELATION = 50;
  static final int MAX_SIZE_EDITION_1_COLUMNS = 90;
  static final int MAX_SIZE_EDITION_2_COLUMNS = 45;
  static final int MAX_TEXTBOX_LENGTH = 110;
  static final double PIXEL_TO_LENGTH = 5.6;
  static final double FIRST_COLS_SIZE = 60;
  static final double SUBTABS_COL_SIZE = 30;
  static final double RELATION_MINIMUM_LENGTH = 15.0;
  static final int IMAGE_RELATION_WIDTH = 16;
  static final int IMAGE_RELATION_HEIGHT = 16;
  static final int IMAGE_BUTTON_WIDTH = 16;
  static final int IMAGE_BUTTON_HEIGHT = 16;
  static final String IMAGE_DEFAULT = "blank.gif";
  XmlEngine xmlEngine;
  protected static WadConnection pool;
  String strSystemSeparator;
  static final String calendarDescription = "Calendar";
  static final String clockDescription = "Clock";
  static final String calculatorDescription = "Calculator";
  static String calendarDescriptionTrl = "";
  static String clockDescriptionTrl = "";
  static String calculatorDescriptionTrl = "";
  static String jsDateFormat;
  static String sqlDateFormat;

  static Logger log4j = Logger.getLogger(Wad.class);

  public static void main(String argv[]) throws Exception {
    PropertyConfigurator.configure("log4j.lcf");
    String strWindowName;
    String dirFin;
    String dirReference;
    String dirWebXml;
    String dirActionButton;
    boolean generateWebXml;
    boolean generateTabs;
    String dirBaseTrl;
    String translateStr;
    String dirWebClients;
    String basePath;
    String attachPath;
    String webPath;
    String strBaseSrc;
    boolean complete;

    if (argv.length < 1) {
      log4j.error("Usage: java Wad connection.xml [{% || Window} [destinyDir]]");
      return;
    }
    String strFileConnection = argv[0];
    Wad wad = new Wad();
    wad.strSystemSeparator = System.getProperty("file.separator");
    wad.createXmlEngine(strFileConnection);
    wad.createPool(strFileConnection + "/XmlPool.xml");
    wad.readProperties(strFileConnection + "/Openbravo.properties");
    try {
      // the second parameter is the tab to be generated
      // if there is none it's * then all them are read
      strWindowName = argv[1];

      // the third parameter is the directory where the tab files are created
      if(argv.length <= 2) dirFin = ".";
      else dirFin = argv[2];

      // the fourth paramenter is the directory where the references are created
      // (TableList_data.xsql y TableDir_data.xsql)
      if(argv.length <= 3) dirReference = dirFin;
      else dirReference = argv[3];

      // the fifth parameter is the directory where web.xml es created
      if(argv.length <= 4) dirWebXml = dirFin;
      else dirWebXml = argv[4];

      // the sixth parementer indicates whether web.xml has to be generated or not
      if(argv.length <= 5) {
        generateWebXml = true;
        generateTabs = true;
      } else if (argv[5].equals("web.xml")) {
        generateWebXml = true;
        generateTabs = false;
      } else if (argv[5].equals("tabs")) {
        generateWebXml = false;
        generateTabs = true;
      } else {
        generateWebXml = true;
        generateTabs = true;
      }

      if(argv.length <= 6) dirActionButton = dirFin;
      else dirActionButton = argv[6];

      if(argv.length <= 7) dirBaseTrl = dirFin;
      else dirBaseTrl = argv[7];

      if(argv.length <= 8) translateStr = "";
      else translateStr = argv[8];

      if(argv.length <= 9) dirWebClients = "";
      else dirWebClients = argv[9];

      if (argv.length <= 10) basePath = dirFin;
      else basePath = argv[10];

      if (argv.length <= 11) attachPath = dirFin;
      else attachPath = argv[11];

      if (argv.length <= 12) webPath = dirFin;
      else webPath = argv[12];

      if (argv.length <= 13) strBaseSrc = dirFin;
      else strBaseSrc = argv[13];

      if (argv.length <= 14) complete = false;
      else complete = ((argv[14].equals("true"))?true:false);

      log4j.info("File connection: " + strFileConnection);
      log4j.info("window: " + strWindowName);
      log4j.info("directory destiny: " + dirFin);
      log4j.info("directory reference: " + dirReference + wad.strSystemSeparator + "reference");
      log4j.info("directory web.xml: " + dirWebXml);
      log4j.info("directory ActionButtons: " + dirActionButton);
      log4j.info("generate web.xml: " + generateWebXml);
      log4j.info("generate web.xml cliente: " + dirWebClients);
      log4j.info("generate tabs: " + generateTabs);
      log4j.info("directory Translate : " + dirBaseTrl);
      log4j.info("translation to : " + translateStr);
      log4j.info("Separador del Sistema: " + wad.strSystemSeparator);
      log4j.info("Base path: " + basePath);
      log4j.info("Attach path: " + attachPath);
      log4j.info("Web path: " + webPath);
      log4j.info("Src path: " + strBaseSrc);
      log4j.info("complete: " + complete);

      File fileFin = new File(dirFin);
      if (!fileFin.exists()) {
        log4j.error("No such directory: " + fileFin.getAbsoluteFile());
        wad.pool.destroy();
        return;
      }

      File fileFinReloads = new File(dirReference + wad.strSystemSeparator + "ad_callouts");
      if (!fileFinReloads.exists()) {
        log4j.error("No such directory: " + fileFinReloads.getAbsoluteFile());
        wad.pool.destroy();
        return;
      }

      File fileReference = new File(dirReference + wad.strSystemSeparator + "reference");
      if (!fileReference.exists()) {
        log4j.error("No such directory: " + fileReference.getAbsoluteFile());
        wad.pool.destroy();
        return;
      }

      File fileWebXml = new File(dirWebXml);
      if (!fileWebXml.exists()) {
        log4j.error("No such directory: " + fileWebXml.getAbsoluteFile());
        wad.pool.destroy();
        return;
      }

      File fileWebXmlClient = null;
      if (dirWebClients!=null && !dirWebClients.equals("")) {
        fileWebXmlClient = new File(dirWebClients);
        if (!fileWebXmlClient.exists()) {
          log4j.warn("No such directory: " + fileWebXmlClient.getAbsoluteFile());
          fileWebXmlClient = null;
        }
      }

      File fileActionButton = new File(dirActionButton);
      if (!fileActionButton.exists()) {
        log4j.error("No such directory: " + fileActionButton.getAbsoluteFile());
        wad.pool.destroy();
        return;
      }

      File fileTrl = new File(dirBaseTrl);
      if (!fileTrl.exists()) {
        log4j.error("No such directory: " + fileTrl.getAbsoluteFile());
        wad.pool.destroy();
        return;
      }

      File fileBase = new File(strBaseSrc);
      if (!fileBase.exists()) {
        log4j.error("No such directory: " + fileBase.getAbsoluteFile());
        wad.pool.destroy();
        return;
      }

      File fileBaseAplication = new File(basePath);
      if (!fileBaseAplication.exists()) {
        log4j.error("No such directory: " + fileBaseAplication.getAbsoluteFile());
        wad.pool.destroy();
        return;
      }

      WadData.updateIdentifiers(wad.pool);
      if (generateTabs) {
        wad.processActionButton(fileReference);
        wad.processActionButtonXml(fileActionButton);
        wad.processActionButtonHtml(fileActionButton);
        wad.processActionButtonGenerics(fileActionButton);
        wad.processActionButtonXmlGenerics(fileActionButton);
        wad.processActionButtonHtmlGenerics(fileActionButton);
        LanguagesData[] dataLang = LanguagesData.select(wad.pool);
        if (dataLang!=null && dataLang.length>0) {
          for (int pos=0;pos<dataLang.length;pos++) {
            FileUtility f = new FileUtility();
            File languageBase = new File(fileTrl, dataLang[pos].adLanguage);
            if (complete && languageBase.exists()) f.delete(languageBase);
            languageBase.mkdir();
            //f.copy(fileBase, languageBase,new DirFilter("html"), true, true);
            //f.copy(fileBase, languageBase,new DirFilter("fo"), true, true);
            f.copy(fileBase, languageBase,new DirFilter(".xml"), true, true);
            //f.copy(fileBase, languageBase,new DirFilter("srpt"), true, true);
            //f.copy(fileBase, languageBase,new DirFilter("jrxml"), true, true);
            //executeCommandTask("ant precopyfiles -Dlanguage=" + dataLang[pos].adLanguage, dir);
            File fileDirTrlBase = new File(fileTrl, dataLang[pos].adLanguage + wad.strSystemSeparator + "org" + wad.strSystemSeparator + "openbravo" + wad.strSystemSeparator +"erpCommon" + wad.strSystemSeparator + "ad_actionButton");
            if (!fileDirTrlBase.exists()) {
              fileDirTrlBase.mkdirs();
            }
            calendarDescriptionTrl = WadUtilityData.getTranslatedText(wad.pool, calendarDescription, dataLang[pos].adLanguage);
            clockDescriptionTrl = WadUtilityData.getTranslatedText(wad.pool, clockDescription, dataLang[pos].adLanguage);
            calculatorDescriptionTrl = WadUtilityData.getTranslatedText(wad.pool, calculatorDescription, dataLang[pos].adLanguage);
            wad.processActionButtonHtmlTrl(fileDirTrlBase, dataLang[pos].adLanguage);
            wad.processActionButtonHtmlGenericsTrl(fileDirTrlBase, dataLang[pos].adLanguage);
          }
        }
      }

      if (generateWebXml) {
        TabsData tabsData[] = TabsData.selectTabs(wad.pool, "");
        wad.processWebXml(fileWebXml, fileWebXmlClient, attachPath, webPath);
      }

      TabsData tabsData[] = TabsData.selectTabs(wad.pool, strWindowName);
      if (generateTabs) {
        for (int i=0;i< tabsData.length; i++) {
          log4j.info("Processing Window: " + tabsData[i].windowname +
            " - Tab: " + tabsData[i].tabname + " - id: " + tabsData[i].tabid);
          log4j.debug("Processing: " + tabsData[i].tabid);
          wad.processTab(fileFin, fileFinReloads, tabsData[i], fileTrl, dirBaseTrl, translateStr, fileBase, fileBaseAplication);
        }
      }
      wad.pool.destroy();
    } catch (Exception e) {
      wad.pool.destroy();
      throw new Exception(e);
    }
  }

  private void processActionButton(File fileReference) {
    try {
      log4j.info("Processing ActionButton_data.xml");
      XmlDocument xmlDocumentData = xmlEngine.readXmlTemplate("org/openbravo/wad/ActionButton_data").createXmlDocument();
      ProcessRelationData ard[] = ProcessRelationData.select(pool);

      xmlDocumentData.setData("structure1", ard);
      WadUtility.writeFile(fileReference, "ActionButton_data.xsql", "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" + xmlDocumentData.print());
    } catch (ServletException e) {
      e.printStackTrace();
      log4j.error("Problem of ServletExceptio in process of ActionButtonData");
    } catch (IOException e) {
      e.printStackTrace();
      log4j.error("Problem of IOExceptio in process of ActionButtonData");
    }
  }

  private void processActionButtonXml(File fileReference) {
    try {
      log4j.info("Processing ActionButtonXml");
      FieldsData fd[] = FieldsData.selectActionButton(pool);
      if (fd!=null) {
        for (int i=0;i<fd.length;i++) {
          Vector<Object> vecFields = new Vector<Object>();
          WadActionButton.buildXml(pool, xmlEngine, fileReference, fd[i], vecFields, MAX_TEXTBOX_LENGTH);
        }
      }
    } catch (ServletException e) {
      e.printStackTrace();
      log4j.error("Problem of ServletExceptio in process of ActionButtonXml");
    } catch (IOException e) {
      e.printStackTrace();
      log4j.error("Problem of IOExceptio in process of ActionButtonXml");
    }
  }

  private void processActionButtonHtml(File fileReference) {
    try {
      log4j.info("Processing ActionButtonHtml");
      FieldsData fd[] = FieldsData.selectActionButton(pool);
      if (fd!=null) {
        for (int i=0;i<fd.length;i++) {
          Vector<Object> vecFields = new Vector<Object>();
          WadActionButton.buildHtml(pool, xmlEngine, fileReference, fd[i], vecFields, MAX_TEXTBOX_LENGTH, MAX_SIZE_EDITION_1_COLUMNS, "", false, calendarDescription, clockDescription, calculatorDescription, jsDateFormat);
        }
      }
    } catch (ServletException e) {
      e.printStackTrace();
      log4j.error("Problem of ServletExceptio in process of ActionButtonHtml");
    } catch (IOException e) {
      e.printStackTrace();
      log4j.error("Problem of IOExceptio in process of ActionButtonHtml");
    }
  }

  private void processActionButtonHtmlTrl(File fileReference, String strLanguage) {
    try {
      log4j.info("Processing ActionButtonHtml - Translated");
      FieldsData fd[] = FieldsData.selectActionButtonTrl(pool, strLanguage);
      if (fd!=null) {
        for (int i=0;i<fd.length;i++) {
          Vector<Object> vecFields = new Vector<Object>();
          WadActionButton.buildHtml(pool, xmlEngine, fileReference, fd[i], vecFields, MAX_TEXTBOX_LENGTH, MAX_SIZE_EDITION_1_COLUMNS, strLanguage, false, calendarDescriptionTrl, clockDescriptionTrl, calculatorDescriptionTrl, jsDateFormat);
        }
      }
    } catch (ServletException e) {
      e.printStackTrace();
      log4j.error("Problem of ServletExceptio in process of ActionButtonHtml - Translated");
    } catch (IOException e) {
      e.printStackTrace();
      log4j.error("Problem of IOExceptio in process of ActionButtonHtml - Translated");
    }
  }

  
  private void processActionButtonGenerics(File fileReference) {
    try {
      log4j.info("Processing ActionButton_Responser.xml");
      XmlDocument xmlDocumentData = xmlEngine.readXmlTemplate("org/openbravo/wad/ActionButton_Responser").createXmlDocument();

      ActionButtonRelationData[] abrd = WadActionButton.buildActionButtonCallGenerics(pool);
      xmlDocumentData.setData("structure1", abrd);
      xmlDocumentData.setData("structure2", abrd);
      xmlDocumentData.setData("structure3", abrd);

      WadUtility.writeFile(fileReference, "ActionButton_Responser.java", xmlDocumentData.print());
    } catch (IOException e) {
      e.printStackTrace();
      log4j.error("Problem of IOExceptio in process of ActionButton_Responser");
    }
  }

  private void processActionButtonXmlGenerics(File fileReference) {
    try {
      log4j.info("Processing ActionButtonXml Generics");
      FieldsData fd[] = FieldsData.selectActionButtonGenerics(pool);
      if (fd!=null) {
        for (int i=0;i<fd.length;i++) {
          Vector<Object> vecFields = new Vector<Object>();
          WadActionButton.buildXml(pool, xmlEngine, fileReference, fd[i], vecFields, MAX_TEXTBOX_LENGTH);
        }
      }
    } catch (ServletException e) {
      e.printStackTrace();
      log4j.error("Problem of ServletExceptio in process of ActionButtonXml Generics");
    } catch (IOException e) {
      e.printStackTrace();
      log4j.error("Problem of IOExceptio in process of ActionButtonXml Generics");
    }
  }

  private void processActionButtonHtmlGenerics(File fileReference) {
    try {
      log4j.info("Processing ActionButtonHtml for generics");
      FieldsData fd[] = FieldsData.selectActionButtonGenerics(pool);
      if (fd!=null) {
        for (int i=0;i<fd.length;i++) {
          Vector<Object> vecFields = new Vector<Object>();
          WadActionButton.buildHtml(pool, xmlEngine, fileReference, fd[i], vecFields, MAX_TEXTBOX_LENGTH, MAX_SIZE_EDITION_1_COLUMNS, "", true, calendarDescription, clockDescription, calculatorDescription, jsDateFormat);
        }
      }
    } catch (ServletException e) {
      e.printStackTrace();
      log4j.error("Problem of ServletExceptio in process of ActionButtonHtml Generics");
    } catch (IOException e) {
      e.printStackTrace();
      log4j.error("Problem of IOExceptio in process of ActionButtonHtml Generics");
    }
  }

  private void processActionButtonHtmlGenericsTrl(File fileReference, String strLanguage) {
    try {
      log4j.info("Processing ActionButtonHtml for generics - Translated");
      FieldsData fd[] = FieldsData.selectActionButtonGenericsTrl(pool, strLanguage);
      if (fd!=null) {
        for (int i=0;i<fd.length;i++) {
          Vector<Object> vecFields = new Vector<Object>();
          WadActionButton.buildHtml(pool, xmlEngine, fileReference, fd[i], vecFields, MAX_TEXTBOX_LENGTH, MAX_SIZE_EDITION_1_COLUMNS, strLanguage, true, calendarDescriptionTrl, clockDescriptionTrl, calculatorDescriptionTrl, jsDateFormat);
        }
      }
    } catch (ServletException e) {
      e.printStackTrace();
      log4j.error("Problem of ServletExceptio in process of ActionButtonHtml Generics - Translated");
    } catch (IOException e) {
      e.printStackTrace();
      log4j.error("Problem of IOExceptio in process of ActionButtonHtml Generics - Translated");
    }
  }

  private void processWebXml(File fileWebXml, File fileClients, String attachPath, String webPath) throws ServletException, IOException {
    try {
      log4j.info("Processing web.xml");
      XmlDocument xmlDocument = xmlEngine.readXmlTemplate("org/openbravo/wad/webConf").createXmlDocument();
      StringBuffer sb = new StringBuffer();

      try {
        if (fileClients!=null) {
          BufferedReader fileBuffer = new BufferedReader(new FileReader(fileClients));

          String nextLine = fileBuffer.readLine();
          while (nextLine != null) {
            sb.append(nextLine).append("\n");
            nextLine = fileBuffer.readLine();
          }
          fileBuffer.close();
        }
      } catch (Exception e) {
        e.printStackTrace();
        return;
      }
      xmlDocument.setParameter("webClients", sb.toString());
      xmlDocument.setParameter("webPath", webPath);
      xmlDocument.setParameter("attachPath", attachPath);
      xmlDocument.setData("structure1", WadData.select(pool));
      xmlDocument.setData("structure2", WadData.selectMapping(pool));
      //WadUtility.writeFile(fileWebXml, "web.xml", "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" + "<!DOCTYPE web-app PUBLIC \"-//Sun Microsystems, Inc.//DTD Web Application 2.2//EN\" \"http://java.sun.com/j2ee/dtds/web-app_2_2.dtd\">\n" + xmlDocument.print());
      WadUtility.writeFile(fileWebXml, "web.xml", "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" + xmlDocument.print());
    } catch (IOException e) {
      e.printStackTrace();
      log4j.error("Problem of IOException in process of Web.xml");
    }
  }


  private void processTab(File fileFin, File fileFinReloads, TabsData tabsData, File fileTrl, String dirBaseTrl, String translateStr, File fileBase, File fileBaseAplication) throws Exception {
    try {
      String tabNamePresentation = tabsData.realtabname;
      String tabName = FormatUtilities.replace(tabNamePresentation);
      String windowName = FormatUtilities.replace(tabsData.windowname);
      String tableName = FieldsData.tableName(pool, tabsData.tabid);
      String isSOTrx = FieldsData.isSOTrx(pool, tabsData.tabid);
      TabsData[] allTabs = getPrimaryTabs(tabsData.key, tabsData.tabid, Integer.valueOf(tabsData.tablevel).intValue(), HEIGHT_TABS, INCR_TABS, "");
      FieldsData[] fieldsData = FieldsData.select(pool, tabsData.tabid);
      EditionFieldsData efd[] = EditionFieldsData.select(pool, tabsData.tabid);
      EditionFieldsData efdauxiliar[] = EditionFieldsData.selectAuxiliar(pool, tabsData.tabid);

      /************************************************
      *    The 2 tab lines generation
      *************************************************/
      if (allTabs==null || allTabs.length==0) throw new Exception("No tabs found for AD_Tab_ID: " + tabsData.tabid + " - key: " + tabsData.key + " - level: " + tabsData.tablevel);
      TabsData[] tab1= new TabsData[(allTabs.length>NUM_TABS)?NUM_TABS:allTabs.length];
      TabsData[] tab2 = new TabsData[(allTabs.length>NUM_TABS)?NUM_TABS:0];
      int selectedTab=2;
      for (int i=0;i<NUM_TABS && i<allTabs.length;i++) {
        if (allTabs[i].tabid.equals(tabsData.tabid)) selectedTab=1;
        tab1[i]=allTabs[i];
      }
      if (allTabs.length>NUM_TABS) {
        int j=0;
        for (int i=allTabs.length-NUM_TABS;i<allTabs.length;i++) tab2[j++]=allTabs[i];
      }

      int parentTabIndex = -1;
      boolean sinParent=false;
      String grandfatherField="";
      if (allTabs!=null && allTabs.length>0) parentTabIndex = parentTabId(allTabs, tabsData.tabid);
      FieldsData[] parentsFieldsData=null;
      FieldsData[] parentsFieldsNameData=null;
      if (tabsData.issorttab.equals("Y")) {
        parentsFieldsData = FieldsData.parentsColumnNameSortTab(pool, (parentTabIndex!=-1?allTabs[parentTabIndex].tabid:""), tabsData.tableId);
        parentsFieldsNameData = FieldsData.parentsColumnDisplayNameSortTab(pool, "", tabsData.tableId);
      } else {
        parentsFieldsData = FieldsData.parentsColumnName(pool, (parentTabIndex!=-1?allTabs[parentTabIndex].tabid:""), tabsData.tabid);
        parentsFieldsNameData = FieldsData.parentsColumnDisplayName(pool, "", tabsData.tabid, (parentTabIndex!=-1?allTabs[parentTabIndex].tabid:""));
      }
      String strParentNameDescription = (parentsFieldsNameData==null || parentsFieldsNameData.length==0)?"":parentsFieldsNameData[0].name;
      if (parentTabIndex!=-1 && (parentsFieldsData==null || parentsFieldsData.length==0)) {
        parentsFieldsData = FieldsData.parentsColumnReal(pool, allTabs[parentTabIndex].tabid, tabsData.tabid);
        parentsFieldsNameData = FieldsData.parentsColumnDisplayNameReal(pool, "", tabsData.tabid, allTabs[parentTabIndex].tabid);
        strParentNameDescription = (parentsFieldsNameData==null || parentsFieldsNameData.length==0)?"":parentsFieldsNameData[0].name;
        sinParent=true;
        if (parentsFieldsData==null || parentsFieldsData.length==0) {
          log4j.error("No key found in parent tab: " + allTabs[parentTabIndex].tabname);
        }
      }

      Vector<Object> vecFields = new Vector<Object>();
      Vector<Object> vecTables = new Vector<Object>();
      Vector<Object> vecWhere = new Vector<Object>();
      Vector<Object> vecOrder = new Vector<Object>();
      Vector<Object> vecParameters = new Vector<Object>();
      Vector<Object> vecTableParameters = new Vector<Object>();
      Vector<Object> vecTotalParameters = new Vector<Object>();
      processTable(parentsFieldsData, tabsData.tabid, vecFields, vecTables, vecWhere, vecOrder, vecParameters, tableName, tabsData.windowtype, tabsData.tablevel, vecTableParameters, fieldsData);
      StringBuffer strFields = new StringBuffer();
      log4j.debug("Executing de select conformation");
      for (int i=0;i<vecTableParameters.size();i++) {
        vecTotalParameters.addElement(vecTableParameters.elementAt(i));
      }
      for (int i=0;i<vecParameters.size();i++) {
        vecTotalParameters.addElement(vecParameters.elementAt(i));
      }
      for (Enumeration e = vecFields.elements() ; e.hasMoreElements() ;) {
        String fieldElement = (String)e.nextElement();
        strFields.append(fieldElement + ", \n");
      }
      log4j.debug("Fields of select: " + strFields.toString());
      StringBuffer strTables = new StringBuffer();
      for (Enumeration e = vecTables.elements() ; e.hasMoreElements() ;) {
        String tableElement = (String)e.nextElement();
        strTables.append((tableElement.trim().toLowerCase().startsWith("left join")?" ":", ") + tableElement);
      }
      log4j.debug("Tables of select: " + strTables.toString());
      StringBuffer strWhere = new StringBuffer();
      for (Enumeration e = vecWhere.elements() ; e.hasMoreElements();) {
        String whereElement = (String)e.nextElement();
        strWhere.append((!whereElement.startsWith(" AND")?" AND ":"") + whereElement);
      }
      String whereClauseParams = "";
      if (!tabsData.whereclause.equals("")) {
        int totalParameters = vecTotalParameters.size();
        strWhere.append(" AND " + WadUtility.buildSQL(tabsData.whereclause, vecTotalParameters));
        if (totalParameters<vecTotalParameters.size()) {
          for (int h=totalParameters;h<vecTotalParameters.size();h++) {
            String strParam = (String)vecTotalParameters.elementAt(h);
            vecParameters.addElement(strParam);
            strParam = strParam.substring(17, strParam.lastIndexOf("\""));
            whereClauseParams += ", Utility.getContext(this, vars, \"" + strParam + "\", windowId)";
          }
        }
      }
      log4j.debug("Where of select: " + strWhere.toString());
      StringBuffer strOrder = new StringBuffer();
      log4j.debug("Order Vector's Size: " + vecOrder.size());
      if (tabsData.orderbyclause.equals("")) {
        if (vecOrder.size() > 0) strOrder.append(" ORDER BY ");
        boolean first=true;
        for (Enumeration e = vecOrder.elements() ; e.hasMoreElements() ;) {
          String orderElement = (String)e.nextElement();
          log4j.debug("Order element: " + orderElement);
          strOrder.append(((!first)?", ":"") + orderElement);
          if (first) first=false;
        }
      } else {
        strOrder.append(" ORDER BY " + tabsData.orderbyclause);
      }
      log4j.debug("Order of select: " + strOrder.toString());
      if (strOrder.toString().equals("")) strOrder.append(" ORDER BY 1");

      EditionFieldsData[] selCol = EditionFieldsData.selectSerchFieldsSelection(pool, "", tabsData.tabid);
      if (selCol==null || selCol.length==0) selCol = EditionFieldsData.selectSerchFields(pool, "", tabsData.tabid);
      selCol = processSelCol(selCol, tableName);


      File fileDir = new File(fileFin, windowName);
      
      int grandfatherTabIndex=-1;
      String parentwhereclause = "";
      FieldsData auxFieldsData[]=null;
      if (parentTabIndex!=-1 && allTabs!=null && allTabs.length>0) {
        parentwhereclause = FieldsData.selectParentWhereClause(pool, allTabs[parentTabIndex].tabid);
        Vector<Object> vecParametersParent = new Vector<Object>();
        WadUtility.buildSQL(parentwhereclause, vecParametersParent);
        parentwhereclause = "";
        if (vecParametersParent.size()>0) {
          for (int h=0;h<vecParametersParent.size();h++) {
            String strParam = (String)vecParametersParent.elementAt(h);
            strParam = strParam.substring(17, strParam.lastIndexOf("\""));
            parentwhereclause += ", Utility.getContext(this, vars, \"" + strParam + "\", windowId)";
          }
        }
        grandfatherTabIndex = parentTabId(allTabs, allTabs[parentTabIndex].tabid);
        auxFieldsData = FieldsData.parentsColumnName(pool, (grandfatherTabIndex!=-1?allTabs[grandfatherTabIndex].tabid:""), allTabs[parentTabIndex].tabid);
        if (grandfatherTabIndex!=-1 && (auxFieldsData==null || auxFieldsData.length==0)) {
          auxFieldsData = FieldsData.parentsColumnReal(pool, allTabs[grandfatherTabIndex].tabid, allTabs[parentTabIndex].tabid);
        }
      }
      if (auxFieldsData!=null && auxFieldsData.length>0) grandfatherField=auxFieldsData[0].name;
      auxFieldsData=null;
      String keyColumnName = "";
      boolean isSecondaryKey = false;
      FieldsData[] dataKey = FieldsData.keyColumnName(pool, tabsData.tabid, ((parentsFieldsData!=null && parentsFieldsData.length>0 && !sinParent)?parentsFieldsData[0].name:" "));
      if (dataKey!=null && dataKey.length>0) {
        keyColumnName = dataKey[0].name;
        isSecondaryKey = dataKey[0].issecondarykey.equals("Y");
      }
      log4j.debug("KeyColumnName: " + keyColumnName);
      String strProcess="", strDirectPrint="";
      if (!tabsData.adProcessId.equals("")) {
        strProcess = TabsData.processName(pool, tabsData.adProcessId);
        if (strProcess.indexOf("/")==-1) strProcess = FormatUtilities.replace(strProcess);
        strDirectPrint = TabsData.directPrint(pool, tabsData.adProcessId);
      }
      WADGrid gridControl = null;
      {
        Properties gridProps = new Properties();
        gridProps.setProperty("id", "grid");
        gridProps.setProperty("NumRows", "20");
        gridProps.setProperty("width", "94%");
        gridProps.setProperty("ShowLineNumbers", "true");
        gridProps.setProperty("editable", "false");
        gridProps.setProperty("sortable", "true");
        gridProps.setProperty("deleteable", (!tabsData.isreadonly.equals("Y")?"true":"false"));
        gridProps.setProperty("onScrollFunction", "updateHeader");
        gridProps.setProperty("onLoadFunction", "onGridLoadDo");
        gridProps.setProperty("AD_Window_ID", tabsData.key);
        gridProps.setProperty("AD_Tab_ID", tabsData.tabid);
        gridProps.setProperty("ColumnName", keyColumnName);
        gridProps.setProperty("inpKeyName", "inp" + Sqlc.TransformaNombreColumna(keyColumnName));
        gridControl = new WADGrid(gridProps);
      }
      if (tabsData.issorttab.equals("Y")) {
        /************************************************
        *             XSQL of the SORT TAB
        *************************************************/
        processTabXSQLSortTab(parentsFieldsData, fileDir, tabsData.tabid, tabName, tableName, windowName, keyColumnName, tabsData.adColumnsortorderId, tabsData.adColumnsortyesnoId, vecParameters, vecTableParameters);
        /************************************************
        *             JAVA of the SORT TAB
        *************************************************/
        processTabJavaSortTab(parentsFieldsData, fileDir, tabsData.tabid, tabName, tableName, windowName, keyColumnName, strTables.toString(), strOrder.toString(), strWhere.toString(), vecFields, isSOTrx, allTabs, tabsData.key, tabsData.accesslevel, selCol, isSecondaryKey, grandfatherField, tabsData.tablevel, tabsData.tableId, tabsData.windowtype, tabsData.adColumnsortorderId, whereClauseParams, parentwhereclause, strProcess, strDirectPrint, tabsData.isreadonly.equals("Y"), vecParameters, vecTableParameters);
        /************************************************
        *             XML of the SORT TAB
        *************************************************/
        processTabXmlSortTab(parentsFieldsData, fileDir, tabsData.tabid, tabName, keyColumnName);
        /************************************************
        *             HTML of the SORT TAB
        *************************************************/
        processTabHtmlSortTab(parentsFieldsData, fileDir, tabsData.tabid, tabName, tabsData.realwindowname, keyColumnName, tabNamePresentation, allTabs, strProcess, strDirectPrint, strParentNameDescription, windowName, "");
      } else {
        /************************************************
        *                     JAVA
        *************************************************/
        processTabJava(efd, efdauxiliar, parentsFieldsData, fileDir, tabsData.tabid, tabName, tableName, windowName, keyColumnName, strTables.toString(), strOrder.toString(), strWhere.toString(), tabsData.filterclause, vecFields, vecParameters, isSOTrx, allTabs, tabsData.key, tabsData.accesslevel, selCol, isSecondaryKey, grandfatherField, tabsData.tablevel, tabsData.tableId, tabsData.windowtype, tabsData.isreadonly.equals("Y"), whereClauseParams, parentwhereclause, tabsData.editreference, strProcess, strDirectPrint, vecTableParameters, fieldsData, gridControl);

        /************************************************
        *                     XSQL
        *************************************************/
        processTabXSQL(parentsFieldsData, fileDir, tabsData.tabid, tabName, tableName, windowName, keyColumnName, strFields.toString(), strTables.toString(), strOrder.toString(), strWhere.toString(), vecParameters, tabsData.filterclause, selCol, tabsData.tablevel, tabsData.windowtype, vecTableParameters, fieldsData);


        /************************************************
        *        JAVA of the combo reloads
        *************************************************/
        processTabComboReloads(fileFinReloads, tabsData.tabid, parentsFieldsData, vecFields, isSOTrx);


        /************************************************
        *             XML in Relation view
        *************************************************/
        processTabXmlRelation(parentsFieldsData, fileDir, tabsData.tabid, tabName, keyColumnName, gridControl);

        /************************************************
        *             HTML in Relation view
        *************************************************/
        processTabHtmlRelation(parentsFieldsData, fileDir, tabsData.tabid, tabName, keyColumnName, tabsData.isreadonly.equals("Y"), strParentNameDescription, gridControl, false, "", tabNamePresentation, tabsData.tableId);

        /************************************************
        *             XML in Edition view
        *************************************************/
        processTabXmlEdition(fileDir, tabsData.tabid, tabName, tabsData.key, tabsData.isreadonly.equals("Y"), efd, efdauxiliar);

        /************************************************
        *             HTML in Edition view
        *************************************************/
        processTabHtmlEdition(efd, efdauxiliar, fileDir, tabsData.tabid, tabName, keyColumnName, tabNamePresentation, tabsData.key, parentsFieldsData, vecFields, tabsData.isreadonly.equals("Y"), isSOTrx, tabsData.tableId, PIXEL_TO_LENGTH, "");
      }

      LanguagesData[] dataLang = LanguagesData.select(pool);
      if (dataLang!=null && dataLang.length>0) {
        for (int pos=0;pos<dataLang.length;pos++) {
          FieldsData parentsFieldsNameLngData[]=null;
          if (tabsData.issorttab.equals("Y")) {
            parentsFieldsNameLngData = FieldsData.parentsColumnDisplayNameSortTab(pool, dataLang[pos].adLanguage, tabsData.tableId);
          } else {
            parentsFieldsNameLngData = FieldsData.parentsColumnDisplayName(pool, dataLang[pos].adLanguage, tabsData.tabid, (parentTabIndex!=-1?allTabs[parentTabIndex].tabid:""));
          }
          if (parentTabIndex!=-1 && (parentsFieldsNameLngData==null || parentsFieldsNameLngData.length==0)) {
            parentsFieldsNameLngData = FieldsData.parentsColumnDisplayNameReal(pool, dataLang[pos].adLanguage, tabsData.tabid, allTabs[parentTabIndex].tabid);
          }
          strParentNameDescription = (parentsFieldsNameLngData==null || parentsFieldsNameLngData.length==0)?"":(parentsFieldsNameLngData[0].columnname.equals("")?parentsFieldsNameLngData[0].name:parentsFieldsNameLngData[0].columnname);
          tabNamePresentation = FieldsData.tabNameTrl(pool, dataLang[pos].adLanguage, tabsData.tabid);
          String realWindowName = FieldsData.windowNameTrl(pool, dataLang[pos].adLanguage, tabsData.tabid);
          File fileDirTrlBase = new File(fileTrl, dataLang[pos].adLanguage + strSystemSeparator + translateStr);
          if (!fileDirTrlBase.exists()) {
            fileDirTrlBase.mkdirs();
          }
          File fileDirTrl = new File(fileDirTrlBase, windowName);
          fileDirTrl.mkdirs();
          TabsData[] allTabstrl = getPrimaryTabs(tabsData.key, tabsData.tabid, Integer.valueOf(tabsData.tablevel).intValue(), HEIGHT_TABS, INCR_TABS, dataLang[pos].adLanguage);
          TabsData[] tab1trl= new TabsData[(allTabstrl.length>NUM_TABS)?NUM_TABS:allTabstrl.length];
          TabsData[] tab2trl = new TabsData[(allTabstrl.length>NUM_TABS)?NUM_TABS:0];
          int selectedTabtrl=2;
          for (int i=0;i<NUM_TABS && i<allTabstrl.length;i++) {
            if (allTabstrl[i].tabid.equals(tabsData.tabid)) selectedTabtrl=1;
            tab1trl[i]=allTabstrl[i];
          }
          if (allTabstrl.length>NUM_TABS) {
            int j=0;
            for (int i=allTabstrl.length-NUM_TABS;i<allTabstrl.length;i++) tab2trl[j++]=allTabstrl[i];
          }

          calendarDescriptionTrl = WadUtilityData.getTranslatedText(pool, calendarDescription, dataLang[pos].adLanguage);
          clockDescriptionTrl = WadUtilityData.getTranslatedText(pool, clockDescription, dataLang[pos].adLanguage);
          calculatorDescriptionTrl = WadUtilityData.getTranslatedText(pool, calculatorDescription, dataLang[pos].adLanguage);
          String strPixelSize = WadData.selectPixelSize(pool, dataLang[pos].adLanguage);
          double pixelSize = PIXEL_TO_LENGTH;
          if (!strPixelSize.equals("")) pixelSize = Double.valueOf(strPixelSize).doubleValue();

          if (tabsData.issorttab.equals("Y")) {
            /************************************************
            *             HTML of the SORT TAB
            *************************************************/
            processTabHtmlSortTab(parentsFieldsData, fileDirTrl, tabsData.tabid, tabName, realWindowName, keyColumnName, tabNamePresentation, allTabstrl, strProcess, strDirectPrint, strParentNameDescription, windowName, dataLang[pos].adLanguage);
          } else {
            EditionFieldsData efdTRL[] = EditionFieldsData.selectTrl(pool, dataLang[pos].adLanguage, tabsData.tabid);
            // ************************************************
            // *             HTML of the Relation view
            //*************************************************
            processTabHtmlRelation(parentsFieldsData, fileDirTrl, tabsData.tabid, tabName, keyColumnName, tabsData.isreadonly.equals("Y"), strParentNameDescription, gridControl, true, dataLang[pos].adLanguage, tabNamePresentation, tabsData.tableId);

            // ************************************************
            // *             HTML of the Edition view
            // *************************************************
            processTabHtmlEdition(efdTRL, efdauxiliar, fileDirTrl, tabsData.tabid, tabName, keyColumnName, tabNamePresentation, tabsData.key, parentsFieldsData, vecFields, tabsData.isreadonly.equals("Y"), isSOTrx, tabsData.tableId, PIXEL_TO_LENGTH, dataLang[pos].adLanguage);

            //processTabHtmlEditionTrl(efd, efdTRL, efdauxiliar, fileDirTrl, tabsData.tabid, tabName, realWindowName, keyColumnName, tabNamePresentation, tab1trl, tab2trl, allTabstrl, selectedTabtrl, tabsData.key, parentsFieldsData, vecFields, strProcess, strDirectPrint, tabsData.isreadonly.equals("Y"), tabsData.tablevel, dataLang[pos].adLanguage, windowName, isSOTrx, tabsData.tableId, pixelSize);
          }
          FileUtility f = new FileUtility();
          File languageBase = new File(fileTrl, dataLang[pos].adLanguage);
          languageBase.mkdir();
          File fTrl = new File(fileBaseAplication, "srcAD");
          f.copy(fTrl, languageBase,new DirFilter("html"), true, false);
          f.copy(fTrl, languageBase,new DirFilter("fo"), true, false);
          f.copy(fTrl, languageBase,new DirFilter("xml"), true, false);
          f.copy(fTrl, languageBase,new DirFilter("srpt"), true, false);
        }
      }

    } catch(ServletException e) {
       e.printStackTrace();
       log4j.error("Problem of ServletException in the file: " + tabsData.tabid);
    } catch(IOException e) {
       e.printStackTrace();
       log4j.error("Problem at close of the file: "+  tabsData.tabid);
    } catch(Exception e) {
      e.printStackTrace();
      log4j.error("Problem at close of the file: "+  tabsData.tabid);
    }
  }

  private EditionFieldsData[] processSelCol(EditionFieldsData[] selCol, String tableName) {
    Vector<Object> vecAuxSelCol = new Vector<Object>(0);
    Vector<Object> vecSelCol = new Vector<Object>(0);
    if (selCol!=null) {
      for (int i=0;i<selCol.length;i++) {
        selCol[i].htmltext = "strParam" + selCol[i].columnname + ".equals(\"\")";
        selCol[i].columnnameinp = FormatUtilities.replace(selCol[i].columnname);
        
        if (WadUtility.isGeneralNumber(selCol[i].reference) || WadUtility.isDecimalNumber(selCol[i].reference) || WadUtility.isPriceNumber(selCol[i].reference) || WadUtility.isIntegerNumber(selCol[i].reference) || WadUtility.isQtyNumber(selCol[i].reference) || WadUtility.isDateField(selCol[i].reference) || WadUtility.isTimeField(selCol[i].reference) || WadUtility.isDateTimeField(selCol[i].reference)) {
          EditionFieldsData aux = new EditionFieldsData();
          aux.adColumnId = selCol[i].adColumnId;
          aux.name = selCol[i].name;
          aux.reference = selCol[i].reference;
          aux.referencevalue = selCol[i].referencevalue;
          aux.adValRuleId = selCol[i].adValRuleId;
          aux.fieldlength = selCol[i].fieldlength;
          aux.displaylength = selCol[i].displaylength;
          aux.columnname = selCol[i].columnname + "_f";
          aux.realcolumnname = selCol[i].realcolumnname;
          aux.columnnameinp = selCol[i].columnnameinp;
          aux.value = selCol[i].value;
          aux.adWindowId = selCol[i].adWindowId;
          aux.htmltext = "strParam" + aux.columnname + ".equals(\"\")";
          selCol[i].xmltext = " + ((strParam" + selCol[i].columnname + ".equals(\"\") || strParam" + selCol[i].columnname + ".equals(\"%\"))?\"\":\" AND ";
          if (WadUtility.isTimeField(selCol[i].reference)) {
            selCol[i].xmltext += "TO_CHAR(" + tableName + "." + selCol[i].realcolumnname + ", 'HH24:MI:SS') >= ";
            selCol[i].xsqltext = "TO_CHAR(" + tableName + "." + selCol[i].realcolumnname + ", 'HH24:MI:SS') >= ";
          } else {
            selCol[i].xmltext += "(" + tableName + "." + selCol[i].realcolumnname + ") >= ";
            selCol[i].xsqltext = tableName + "." + selCol[i].realcolumnname + " >= ";
          }
          if (WadUtility.isDateField(selCol[i].reference) || WadUtility.isTimeField(selCol[i].reference) || WadUtility.isDateTimeField(selCol[i].reference)) {
            selCol[i].xmltext += "TO_DATE('";
            selCol[i].xsqltext += "TO_DATE";
          }
          selCol[i].xmltext += "\" + strParam" + selCol[i].columnname + " + \"";
          if (WadUtility.isTimeField(selCol[i].reference)) selCol[i].xmltext += "', 'HH24:MI:SS')";
          else if (WadUtility.isDateField(selCol[i].reference) || WadUtility.isDateTimeField(selCol[i].reference)) selCol[i].xmltext += "')";
          selCol[i].xmltext += " \")";
          selCol[i].xsqltext += "(?" + (WadUtility.isTimeField(selCol[i].reference)?", 'HH24:MI:SS'":"") + ") ";
          aux.columnnameinp = FormatUtilities.replace(selCol[i].columnname) + "_f";
          aux.xmltext = " + ((strParam" + aux.columnname + ".equals(\"\") || strParam" + aux.columnname + ".equals(\"%\"))?\"\":\" AND";
          if (WadUtility.isTimeField(selCol[i].reference)) {
            aux.xmltext += "TO_CHAR(" + tableName + "." + aux.realcolumnname + ", 'HH24:MI:SS') < ";
            aux.xsqltext = "TO_CHAR(" + tableName + "." + aux.realcolumnname + ", 'HH24:MI:SS') < ";
          } else {
            aux.xmltext += "(" + tableName + "." + aux.realcolumnname + ") < ";
            aux.xsqltext = tableName + "." + aux.realcolumnname + " < ";
          }

          if (WadUtility.isDateField(selCol[i].reference) || WadUtility.isTimeField(selCol[i].reference) || WadUtility.isDateTimeField(selCol[i].reference)) {
            aux.xmltext += "TO_DATE('";
            aux.xsqltext += "TO_DATE";
          } else if (WadUtility.isGeneralNumber(selCol[i].reference) || WadUtility.isDecimalNumber(selCol[i].reference) || WadUtility.isPriceNumber(selCol[i].reference) || WadUtility.isIntegerNumber(selCol[i].reference) || WadUtility.isQtyNumber(selCol[i].reference) || selCol[i].reference.equals("13")) {
            aux.xmltext += "TO_NUMBER('";
            aux.xsqltext += "TO_NUMBER";
          }
          aux.xmltext += "\" + strParam" + aux.columnname + " + \"";
          if (WadUtility.isTimeField(selCol[i].reference)) aux.xmltext += "', 'HH24:MI:SS')";
          else if (WadUtility.isDateField(selCol[i].reference) || WadUtility.isDateTimeField(selCol[i].reference)) aux.xmltext += "')";
          else if (WadUtility.isGeneralNumber(selCol[i].reference) || WadUtility.isDecimalNumber(selCol[i].reference) || WadUtility.isPriceNumber(selCol[i].reference) || WadUtility.isIntegerNumber(selCol[i].reference) || WadUtility.isQtyNumber(selCol[i].reference) || selCol[i].reference.equals("13")) aux.xmltext += "')";
          aux.xmltext += " + 1 \")";
          aux.xsqltext += "(?" + (WadUtility.isTimeField(selCol[i].reference)?", 'HH24:MI:SS'":"") + ") + 1 ";
          vecAuxSelCol.addElement(aux);
        } else {
          selCol[i].xmltext = " + ((strParam" + selCol[i].columnname + ".equals(\"\") || strParam" + selCol[i].columnname + ".equals(\"%\"))?\"\":\" AND ";
          if (WadUtility.isLikeType(selCol[i].reference) && !WadUtility.isSearchValueColumn(selCol[i].realcolumnname)) {
            selCol[i].xmltext += "C_IGNORE_ACCENT";
          }
          selCol[i].xmltext += "(" + tableName + "." + selCol[i].realcolumnname + ")";
          if (WadUtility.isLikeType(selCol[i].reference) && !WadUtility.isSearchValueColumn(selCol[i].realcolumnname)) {
            selCol[i].xmltext += " LIKE C_IGNORE_ACCENT('";
          } else if (WadUtility.isLikeType(selCol[i].reference) && WadUtility.isSearchValueColumn(selCol[i].realcolumnname)) {
            selCol[i].xmltext += " LIKE ('";
          } else {
            selCol[i].xmltext += " = (";
            if (WadUtility.isTextData(selCol[i].reference) || WadUtility.isLikeType(selCol[i].reference)) selCol[i].xmltext += "'";
          }
          selCol[i].xmltext += "\" + strParam" + selCol[i].columnname + " + \"";
          if (WadUtility.isLikeType(selCol[i].reference)) {
            selCol[i].xmltext += "'";
          } else if (WadUtility.isTextData(selCol[i].reference)) {
            selCol[i].xmltext += "'";
          }
          selCol[i].xmltext += ") \")";
          selCol[i].xsqltext = "";
          if (WadUtility.isLikeType(selCol[i].reference) && !WadUtility.isSearchValueColumn(selCol[i].realcolumnname)) {
            selCol[i].xsqltext = "C_IGNORE_ACCENT";
          }
          selCol[i].xsqltext += "(" + tableName + "." + selCol[i].realcolumnname + ")";
          if (WadUtility.isLikeType(selCol[i].reference) && !WadUtility.isSearchValueColumn(selCol[i].realcolumnname)) {
            selCol[i].xsqltext += " LIKE C_IGNORE_ACCENT";
          } else if (WadUtility.isLikeType(selCol[i].reference) && WadUtility.isSearchValueColumn(selCol[i].realcolumnname)) {
            selCol[i].xsqltext += " LIKE ";
          } else {
            selCol[i].xsqltext += " = ";
          }
          selCol[i].xsqltext += "(?)";
          //selCol[i].xsqltext += " AND ";
        }

        vecSelCol.addElement(selCol[i]);
      }
      for (int i=0;i<vecAuxSelCol.size();i++) vecSelCol.addElement(vecAuxSelCol.elementAt(i));
      selCol = new EditionFieldsData[vecSelCol.size()];
      vecSelCol.copyInto(selCol);
    }
    return selCol;
  }


  private void processTable(FieldsData[] parentsFieldsData, String strTab, Vector<Object> vecFields, Vector<Object> vecTables, Vector<Object> vecWhere, Vector<Object> vecOrder, Vector<Object> vecParameters, String tableName, String windowType, String tablevel, Vector<Object> vecTableParameters, FieldsData[] fieldsDataSelectAux) throws ServletException, IOException {
    int ilist = 0;
    int itable = 0;
    Vector<Object> vecCounters = new Vector<Object>();
    Vector<Object> vecOrderAux = new Vector<Object>();
    String strOrder = "";
    vecCounters.addElement(Integer.toString(itable));
    vecCounters.addElement(Integer.toString(ilist));
    FieldsData[] fieldsData = null;
    fieldsData=copyarray(fieldsDataSelectAux);
    for (int i=0;i< fieldsData.length; i++) {
      if (!fieldsData[i].columnname.equalsIgnoreCase("Created") && !fieldsData[i].columnname.equalsIgnoreCase("CreatedBy") && !fieldsData[i].columnname.equalsIgnoreCase("Updated") && !fieldsData[i].columnname.equalsIgnoreCase("UpdatedBy")) {
        if (WadUtility.isTimeField(fieldsData[i].reference)) {
          vecFields.addElement("TO_CHAR(" + tableName + "." + fieldsData[i].name + ", 'HH24:MI:SS') AS " + fieldsData[i].name);
        } else if (fieldsData[i].reference.equals("20")) {
          vecFields.addElement("COALESCE(" + tableName + "." + fieldsData[i].name + ", 'N') AS " + fieldsData[i].name);
        } else vecFields.addElement(tableName + "." + fieldsData[i].name);
        if (fieldsData[i].reference.equals("19") &&  // TableDir
            fieldsData[i].isdisplayed.equals("Y")) {
          Vector<Object> vecSubFields = new Vector<Object>();
          WadUtility.columnIdentifier (pool, tableName, fieldsData[i].required.equals("Y"), fieldsData[i], vecCounters, false, vecSubFields, vecTables, vecWhere, vecParameters, vecTableParameters, sqlDateFormat);
          log4j.debug("Identifier of: " + fieldsData[i].name);
          StringBuffer strFields = new StringBuffer();
          strFields.append(" (");
          boolean boolFirst = true;
          for (Enumeration e = vecSubFields.elements() ; e.hasMoreElements() ;) {
            String tableField = (String)e.nextElement();
            log4j.debug("  field: " + tableField);
            if (boolFirst) {
              boolFirst = false;
            } else {
              strFields.append(" || ' - ' || ");
            }
            strFields.append("TO_CHAR(").append(tableField).append(") ");
          }
          strOrder = strFields.toString() + ")";
          vecFields.addElement("(CASE WHEN " + tableName + "." + fieldsData[i].name + " IS NULL THEN '' ELSE " + strFields.toString() + ") END) AS " + fieldsData[i].name + "R");
        } else if (fieldsData[i].reference.equals("17") && fieldsData[i].isdisplayed.equals("Y")) {  // List
          Vector<Object> vecSubFields = new Vector<Object>();
          WadUtility.columnIdentifier (pool, tableName, fieldsData[i].required.equals("Y"), fieldsData[i], vecCounters, false, vecSubFields, vecTables, vecWhere, vecParameters, vecTableParameters, sqlDateFormat);
          StringBuffer strFields = new StringBuffer();
          strFields.append(" ( ");
          boolean boolFirst = true;
          for (Enumeration e = vecSubFields.elements() ; e.hasMoreElements() ;) {
            String tableField = (String)e.nextElement();
            log4j.debug("  field: " + tableField);
            if (boolFirst) {
              boolFirst = false;
            } else {
              strFields.append(" || ' - ' || ");
            }
            strFields.append("TO_CHAR(").append(tableField).append(") ");
          }
          strOrder = strFields.toString() + ")";
          vecFields.addElement("(CASE WHEN " + tableName + "." + fieldsData[i].name + " IS NULL THEN '' ELSE " + strFields.toString() + ") END) AS " + fieldsData[i].name + "R");
        } else if (fieldsData[i].reference.equals("18") && fieldsData[i].isdisplayed.equals("Y")) {  // Table
          Vector<Object> vecSubFields = new Vector<Object>();
          WadUtility.columnIdentifier (pool, tableName, fieldsData[i].required.equals("Y"), fieldsData[i], vecCounters, false, vecSubFields, vecTables, vecWhere, vecParameters, vecTableParameters, sqlDateFormat);
          StringBuffer strFields = new StringBuffer();
          strFields.append(" ( ");
          boolean boolFirst = true;
          for (Enumeration e = vecSubFields.elements() ; e.hasMoreElements() ;) {
            String tableField = (String)e.nextElement();
            log4j.debug("  field: " + tableField);
            if (boolFirst) {
              boolFirst = false;
            } else {
              strFields.append(" || ' - ' || ");
            }
            strFields.append("TO_CHAR(").append(tableField).append(") ");
          }
          strOrder = strFields.toString() + ")";
          vecFields.addElement("(CASE WHEN " + tableName + "." + fieldsData[i].name + " IS NULL THEN '' ELSE " + strFields.toString() + ") END) AS " + fieldsData[i].name + "R");
        } else if (fieldsData[i].reference.equals("32") && fieldsData[i].isdisplayed.equals("Y")) {
          Vector<Object> vecSubFields = new Vector<Object>();
          WadUtility.columnIdentifier(pool, tableName, fieldsData[i].required.equals("Y"), fieldsData[i], vecCounters, false, vecSubFields, vecTables, vecWhere, vecParameters, vecTableParameters, sqlDateFormat);
          StringBuffer strFields = new StringBuffer();
          strFields.append(" ( ");
          boolean boolFirst = true;
          for (Enumeration e = vecSubFields.elements() ; e.hasMoreElements() ;) {
            String tableField = (String)e.nextElement();
            log4j.debug("  field: " + tableField);
            if (boolFirst) {
              boolFirst = false;
            } else {
              strFields.append(" || ' - ' || ");
            }
            strFields.append("TO_CHAR(").append(tableField).append(") ");
          }
          strOrder = strFields.toString() + ")";
          vecFields.addElement("(CASE WHEN " + tableName + "." + fieldsData[i].name + " IS NULL THEN '" + IMAGE_DEFAULT + "' ELSE " + strFields.toString() + ") END) AS " + fieldsData[i].name + "R");
        } else if ((fieldsData[i].reference.equals("30") || fieldsData[i].reference.equals("31") || fieldsData[i].reference.equals("35") || fieldsData[i].reference.equals("25") || fieldsData[i].reference.equals("800011")) && fieldsData[i].isdisplayed.equals("Y")) {  //Searchs
          Vector<Object> vecSubFields = new Vector<Object>();
          WadUtility.columnIdentifier(pool, tableName, fieldsData[i].required.equals("Y"), fieldsData[i], vecCounters, false, vecSubFields, vecTables, vecWhere, vecParameters, vecTableParameters, sqlDateFormat);
          log4j.debug("Identifier of: " + fieldsData[i].name);
          StringBuffer strFields = new StringBuffer();
          strFields.append(" (");
          boolean boolFirst = true;
          for (Enumeration e = vecSubFields.elements() ; e.hasMoreElements() ;) {
            String tableField = (String)e.nextElement();
            log4j.debug("  field: " + tableField);
            if (boolFirst) {
              boolFirst = false;
            } else {
              strFields.append(" || ' - ' || ");
            }
            strFields.append("TO_CHAR(").append(tableField).append(") ");
          }
          strOrder = strFields.toString() + ")";
          vecFields.addElement("(CASE WHEN " + tableName + "." + fieldsData[i].name + " IS NULL THEN '' ELSE " + strFields.toString() + ") END) AS " + fieldsData[i].name + "R");
        } else if (fieldsData[i].reference.equals("21") && fieldsData[i].isdisplayed.equals("Y")) {  //Location
          StringBuffer strFields = new StringBuffer();
          strFields.append(" (CASE WHEN " + tableName + "." + fieldsData[i].columnname + " IS NULL THEN '' ELSE TO_CHAR(C_Location_Identifier(" + tableName + "." + fieldsData[i].columnname + ")) END)");
          log4j.debug("Location field: " + strFields.toString());
          strOrder = strFields.toString();
          strFields.append(" AS " + fieldsData[i].name + "R");
          vecFields.addElement(strFields.toString());
        } else if (fieldsData[i].reference.equals("28") && fieldsData[i].isdisplayed.equals("Y") && !fieldsData[i].referencevalue.equals("") && !fieldsData[i].name.equalsIgnoreCase("ChangeProjectStatus")) { //Button
          ilist = Integer.valueOf(vecCounters.elementAt(1).toString()).intValue();
          ilist++;
          vecFields.addElement("list" + ilist + ".name as " + fieldsData[i].name + "_BTN");
          strOrder = "list" + ilist + ".name";
          StringBuffer strWhere = new StringBuffer();
          if (fieldsData[i].name.equalsIgnoreCase("DocAction")) {
            strWhere.append(" AND (CASE " + tableName + "." + fieldsData[i].name + " WHEN '--' THEN 'CL' ELSE TO_CHAR(" + tableName + "." + fieldsData[i].name + ") END) = " + "list" + ilist + ".value");
          } else {
            strWhere.append(" AND " + tableName + "." + fieldsData[i].name + " = " + "list" + ilist + ".value");
          }
          vecTables.addElement("left join ad_ref_list_v list" + ilist + " on (" + "list" + ilist + ".ad_reference_id = " + fieldsData[i].referencevalue + " and list" + ilist + ".ad_language = ? " + strWhere.toString() + ")");
          vecTableParameters.addElement("<Parameter name=\"paramLanguage\"/>");
          vecCounters.set(1, Integer.toString(ilist));
        } else {
          strOrder = tableName + "." + fieldsData[i].name;
        }
        if (!fieldsData[i].reference.equals("23") && !fieldsData[i].reference.equals("14") && !fieldsData[i].reference.equals("34") && !fieldsData[i].reference.equals("13") && !fieldsData[i].reference.equals("26") && !fieldsData[i].reference.equals("32") && !fieldsData[i].sortno.equals("")) {
          String[] aux={new String(fieldsData[i].name), new String(strOrder + (fieldsData[i].name.equalsIgnoreCase("DocumentNo")?" DESC":""))};
          vecOrderAux.addElement(aux);
        }
      }
    }
    FieldsData sfd1[] = FieldsData.selectSequence(pool, strTab);
    if (sfd1!=null && sfd1.length > 0) {
      for (int i=0;i<sfd1.length;i++) {
        String aux = findOrderVector(vecOrderAux, sfd1[i].name);
        if (aux!=null && aux.length()>0) vecOrder.addElement(aux);
      }
    }
  }

  private String findOrderVector(Vector<Object> vecOrder, String name) {
    if (vecOrder.size()==0 || name.equals("")) return "";
    for (int i=0;i<vecOrder.size();i++) {
      String[] aux = (String[]) vecOrder.elementAt(i);
      if (aux[0].equalsIgnoreCase(name)) return aux[1];
    }
    return "";
  }


  private void processTabJavaSortTab(FieldsData[] parentsFieldsData, File fileDir, String strTab, String tabName, String tableName, String windowName, String keyColumnName, String strTables, String strOrder, String strWhere, Vector<Object> vecFields, String isSOTrx, TabsData[] allTabs, String strWindow, String accesslevel, EditionFieldsData[] selCol, boolean isSecondaryKey, String grandfatherField, String tablevel, String tableId, String windowType, String strColumnSortOrderId, String whereClauseParams, String parentwhereclause, String strProcess, String strDirectPrint, boolean strReadOnly, Vector<Object> vecParametersTop, Vector<Object> vecTableParametersTop) throws ServletException, IOException {
    log4j.debug("Processing Sort Tab java: " + strTab + ", " + tabName);
    XmlDocument xmlDocument;
    int parentTab = parentTabId(allTabs, strTab);
    String hasTree = TableLinkData.hasTree(pool, strTab);
    
    String[] discard = {"", "", ""};
    if (parentsFieldsData==null || parentsFieldsData.length == 0) {
      discard[0] = "parent";  // remove the parent tags
    }
    //if (tableName.toUpperCase().startsWith("M_PRODUCT") || tableName.toUpperCase().startsWith("C_BP") || tableName.toUpperCase().startsWith("AD_ORG")) discard[1] = "org";
    if (grandfatherField.equals("")) discard[2]="grandfather";
    xmlDocument = xmlEngine.readXmlTemplate("org/openbravo/wad/javasourceSortTab", discard).createXmlDocument();
    
    fileDir.mkdirs();
    xmlDocument.setParameter("class", tabName);
    xmlDocument.setParameter("package", windowName);
    xmlDocument.setParameter("key", keyColumnName);
    xmlDocument.setParameter("grandfatherName", grandfatherField);
    xmlDocument.setParameter("ShowName", FieldsData.columnName(pool, strColumnSortOrderId));
    if (parentsFieldsData.length > 0) {
      xmlDocument.setParameter("keyParent", parentsFieldsData[0].name);
      xmlDocument.setParameter("keyParentINP", Sqlc.TransformaNombreColumna(parentsFieldsData[0].name));
    }
    xmlDocument.setParameter("keyData", Sqlc.TransformaNombreColumna(keyColumnName));
    xmlDocument.setParameter("windowId", strWindow);
    xmlDocument.setParameter("tabId", strTab);
    xmlDocument.setParameter("tableLevel", accesslevel);
    xmlDocument.setParameter("whereClauseParams", whereClauseParams);
    xmlDocument.setParameter("parentwhereclause", parentwhereclause);
    xmlDocument.setParameter("reportPDF", strProcess);
    xmlDocument.setParameter("reportDirectPrint", strDirectPrint);
    xmlDocument.setParameter("hasTree", hasTree);
    xmlDocument.setParameter("isReadOnly", (strReadOnly?"Y":"N"));
    if (WadUtility.findField(vecFields, "adClientId")) xmlDocument.setParameter("clientId", "data.adClientId");
    else xmlDocument.setParameter("clientId", "Utility.getContext(this, vars, \"#AD_Client_ID\", windowId)");
    
    if (WadUtility.findField(vecFields, "adOrgId")) xmlDocument.setParameter("orgId", "data.adOrgId");
    else xmlDocument.setParameter("orgId", "Utility.getContext(this, vars, \"#AD_Org_ID\", windowId)");
    
    //Parent field language
    if (parentsFieldsData!=null && parentsFieldsData.length>0) {
      Vector<Object> vecCounters2 = new Vector<Object>();
      Vector<Object> vecFields2 = new Vector<Object>();
      Vector<Object> vecTable2 = new Vector<Object>();
      Vector<Object> vecWhere2 = new Vector<Object>();
      Vector<Object> vecParameters2 = new Vector<Object>();
      Vector<Object> vecTableParameters2 = new Vector<Object>();
      vecCounters2.addElement("0");
      vecCounters2.addElement("0");
      WadUtility.columnIdentifier (pool, parentsFieldsData[0].tablename, true, parentsFieldsData[0], vecCounters2, true, vecFields2, vecTable2, vecWhere2, vecParameters2, vecTableParameters2, sqlDateFormat);
      
      xmlDocument.setParameter("parentLanguage", (vecParameters2.size()>0 || vecTableParameters2.size()>0)?", vars.getLanguage()":"");
    }
    //Fields of the parent Session
    FieldsData[] fieldsParentSession = null;
    FieldsData[] auxiliarPFields=null;
    if (parentTab!=-1) {
      xmlDocument.setParameter("parentClass", FormatUtilities.replace(allTabs[parentTab].tabname));
      fieldsParentSession = FieldsData.selectSession(pool, allTabs[parentTab].tabid);
      for (int i=0;i< fieldsParentSession.length; i++) {
        fieldsParentSession[i].name = Sqlc.TransformaNombreColumna(fieldsParentSession[i].name);
        if (fieldsParentSession[i].reference.equals("20")) {
          fieldsParentSession[i].xmltext = ", \"N\"";
        } else {
          fieldsParentSession[i].xmltext = "";
        }
      }
      //Auxiliary fields of the parent
      Vector<Object> vecAuxiliarPFields = new Vector<Object>();
      auxiliarPFields = FieldsData.selectAuxiliar(pool, "", allTabs[parentTab].tabid);
      if (auxiliarPFields!=null) {
        for (int i=0;i<auxiliarPFields.length;i++) {
          auxiliarPFields[i].columnname = Sqlc.TransformaNombreColumna(auxiliarPFields[i].columnname);
          if (auxiliarPFields[i].defaultvalue.toUpperCase().startsWith("@SQL=")) {
            auxiliarPFields[i].defaultvalue = FormatUtilities.replace(allTabs[parentTab].tabname) + "Data.selectAux" + auxiliarPFields[i].reference + "(this" + WadUtility.getWadContext(auxiliarPFields[i].defaultvalue, vecFields, vecAuxiliarPFields, parentsFieldsData, false, isSOTrx, strWindow) + ")";
          } else if (auxiliarPFields[i].defaultvalue.indexOf("@")!=-1) {
            auxiliarPFields[i].defaultvalue = WadUtility.getTextWadContext(auxiliarPFields[i].defaultvalue, vecFields, vecAuxiliarPFields, parentsFieldsData, false, isSOTrx, strWindow);
          } else {
            auxiliarPFields[i].defaultvalue = "\"" + auxiliarPFields[i].defaultvalue + "\"";
          }
          vecAuxiliarPFields.addElement(auxiliarPFields[i].name);
        }
      }
    } else {
      fieldsParentSession = FieldsData.set();
      auxiliarPFields = FieldsData.set();
    }

    xmlDocument.setData("structure8", fieldsParentSession);
    xmlDocument.setData("structure11", auxiliarPFields);
    WadUtility.writeFile(fileDir, tabName + ".java", xmlDocument.print());
  }


  private void processTabJava(EditionFieldsData[] allfields, EditionFieldsData[] auxiliarsData, FieldsData[] parentsFieldsData, File fileDir, String strTab, String tabName, String tableName, String windowName, String keyColumnName, String strTables, String strOrder, String strWhere, String strFilter, Vector<Object> vecFields, Vector<Object> vecParametersTop, String isSOTrx, TabsData[] allTabs, String strWindow, String accesslevel, EditionFieldsData[] selCol, boolean isSecondaryKey, String grandfatherField, String tablevel, String tableId, String windowType, boolean strReadOnly, String whereClauseParams, String parentwhereclause, String editReference, String strProcess, String strDirectPrint, Vector<Object> vecTableParametersTop, FieldsData[] fieldsDataSelectAux, WADControl relationControl) throws ServletException, IOException {
    log4j.debug("Processing java: " + strTab + ", " + tabName);
    XmlDocument xmlDocument;
    boolean isHighVolumen = (FieldsData.isHighVolume(pool, strTab).equals("Y"));
    boolean hasParentsFields = true;
    String createFromProcess = FieldsData.hasCreateFromButton(pool, strTab);
    boolean hasCreateFrom = !createFromProcess.equals("0");
    String postedProcess = FieldsData.hasPostedButton(pool, strTab);
    boolean hasPosted = !postedProcess.equals("0");
    String strhasEncryption = FieldsData.hasEncryptionFields(pool, strTab);
    boolean hasEncryption = (strhasEncryption!=null&&!strhasEncryption.equals("0"));
    int parentTab = parentTabId(allTabs, strTab);
    String hasTree = TableLinkData.hasTree(pool, strTab);
    StringBuffer dl = new StringBuffer();
    //Auxiliary fields of the window
    Vector<Object> vecAuxiliarFields = new Vector<Object>();
    FieldsData[] auxiliarFields = FieldsData.selectAuxiliar(pool, "", strTab);
    if (auxiliarFields!=null) {
      for (int i=0;i<auxiliarFields.length;i++) {
        auxiliarFields[i].columnname = Sqlc.TransformaNombreColumna(auxiliarFields[i].columnname);
        if (auxiliarFields[i].defaultvalue.toUpperCase().startsWith("@SQL=")) {
          auxiliarFields[i].defaultvalue = tabName + "Data.selectAux" + auxiliarFields[i].reference + "(this" + WadUtility.getWadContext(auxiliarFields[i].defaultvalue, vecFields, vecAuxiliarFields, parentsFieldsData, false, isSOTrx, strWindow) + ")";
        } else if (auxiliarFields[i].defaultvalue.indexOf("@")!=-1) {
          auxiliarFields[i].defaultvalue = WadUtility.getTextWadContext(auxiliarFields[i].defaultvalue, vecFields, vecAuxiliarFields, parentsFieldsData, false, isSOTrx, strWindow);
        } else {
          auxiliarFields[i].defaultvalue = "\"" + auxiliarFields[i].defaultvalue + "\"";
        }
        vecAuxiliarFields.addElement(auxiliarFields[i].name);
      }
    }

    {
      Vector<Object> vecContext = new Vector<Object>();
      Vector<Object> vecDL = new Vector<Object>();
      EditionFieldsData[] efd = EditionFieldsData.selectDisplayLogic(pool, strTab);
      if (efd!=null) {
        for (int i=0;i<efd.length;i++)
          WadUtility.displayLogic(efd[i].displaylogic, vecDL, parentsFieldsData, vecAuxiliarFields, vecFields, strWindow, vecContext);
      }
      for (int i=0;i<vecContext.size();i++) {
        dl.append("var str");
        dl.append(FormatUtilities.replace(vecContext.elementAt(i).toString()));
        dl.append("=\\\"\" + Utility.getContext(this, vars, \"");
        dl.append(vecContext.elementAt(i).toString());
        dl.append("\", windowId) + \"\\\";\\n");
      }
    }

    
    String[] discard = {"", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "hasReference"};
    if (parentsFieldsData==null || parentsFieldsData.length == 0) {
      discard[0] = "parent";  // remove the parent tags
      hasParentsFields=false;
    }
    if (tableName.toUpperCase().endsWith("_ACCESS")) {
      discard[18] = "client";
      discard[1] = "org";
    } //else if (tableName.toUpperCase().startsWith("M_PRODUCT") || tableName.toUpperCase().startsWith("C_BP") || tableName.toUpperCase().startsWith("AD_ORG")) discard[1] = "org";
    if (dl.toString().equals("")) discard[2] = "selDisplayLogic";
    if (!isHighVolumen || !tablevel.equals("0")) {
      discard[3] = "sectionIsHighVolume";
    }
    if (selCol==null || selCol.length==0) {
      discard[4] = "sectionIsHighVolume2";
      discard[5] = "sectionIsHighVolume3";
      discard[6] = "sectionIsHighVolume5";
      discard[7] = "sectionIsHighVolumeEdit";
      discard[8] = "sectionIsHighVolume2Edit";
      discard[9] = "sectionIsHighVolume3Edit";
      discard[14] = "sectionIsHighVolume4";
    }
    if (isHighVolumen) discard[10] = "sectionNotIsHighVolume";
    if (isSecondaryKey) discard[11] = "keySequence";
    if (grandfatherField.equals("")) discard[12]="grandfather";
    if (!hasCreateFrom) discard[13]="sectionCreateFrom";
    if (!hasPosted) discard[19]="sectionPosted";
    if (!(windowType.equalsIgnoreCase("T") && tablevel.equals("0"))) discard[15]="isTransactional";
    if (strFilter.trim().equals("")) discard[16]="sectionFilter";
    if (!strReadOnly) discard[17]="sectionReadOnly";
    if (!hasEncryption) discard[20]="encryptionsFields";
    if (!editReference.equals("")) discard[21]="NothasReference";
    xmlDocument = xmlEngine.readXmlTemplate("org/openbravo/wad/javasource", discard).createXmlDocument();
    
    fileDir.mkdirs();
    xmlDocument.setParameter("class", tabName);
    xmlDocument.setParameter("package", windowName);
    xmlDocument.setParameter("key", keyColumnName);
    xmlDocument.setParameter("from", generateStaticWhere(strTables, vecTableParametersTop));
    xmlDocument.setParameter("order", (!strOrder.equals("")?strOrder.substring(9):strOrder));
    Vector<Object> vecTotalParameters = new Vector<Object>();
    for (int i=0;i<vecTableParametersTop.size();i++) {
      vecTotalParameters.addElement(vecTableParametersTop.elementAt(i));
    }
    for (int i=0;i<vecParametersTop.size();i++) {
      vecTotalParameters.addElement(vecParametersTop.elementAt(i));
    }
    xmlDocument.setParameter("where", generateStaticWhere(strWhere, vecParametersTop));
    xmlDocument.setParameter("filter", strFilter);
    xmlDocument.setParameter("displayLogic", dl.toString());
    xmlDocument.setParameter("grandfatherName", grandfatherField);
    xmlDocument.setParameter("defaultView", (FieldsData.isSingleRow(pool, strTab).equals("Y")?"EDIT":"RELATION"));
    xmlDocument.setParameter("whereClauseParams", whereClauseParams);
    xmlDocument.setParameter("parentwhereclause", parentwhereclause);
    xmlDocument.setParameter("reportPDF", strProcess);
    xmlDocument.setParameter("reportDirectPrint", strDirectPrint);
    xmlDocument.setParameter("relationControl", relationControl.toJava());
    if (parentsFieldsData.length > 0) {
      xmlDocument.setParameter("keyParent", parentsFieldsData[0].name);
      xmlDocument.setParameter("keyParentINP", Sqlc.TransformaNombreColumna(parentsFieldsData[0].name));
    }
    xmlDocument.setParameter("keyData", Sqlc.TransformaNombreColumna(keyColumnName));
    xmlDocument.setParameter("table", tableName);
    xmlDocument.setParameter("windowId", strWindow);
    xmlDocument.setParameter("tabId", strTab);
    xmlDocument.setParameter("tableLevel", accesslevel);
    xmlDocument.setParameter("tableId", tableId);
    xmlDocument.setParameter("createFromProcessId", ((Integer.valueOf(createFromProcess).intValue()>0)?createFromProcess:""));
    xmlDocument.setParameter("postedProcessId", ((Integer.valueOf(postedProcess).intValue()>0)?postedProcess:""));
    xmlDocument.setParameter("editReference", TabsData.formClassName(pool, editReference));
    xmlDocument.setParameter("hasTree", hasTree);
    xmlDocument.setParameter("isReadOnly", (strReadOnly?"Y":"N"));

    String strHighVolume="", strParamHighVolume="", strHighVolumeComp="";
    
    if (selCol!=null) {
      for (int i=0;i<selCol.length;i++) {
        strHighVolume += selCol[i].htmltext;
        strParamHighVolume += "String strParam" + selCol[i].columnname + " = vars.getSessionValue(tabId + \"|param" + selCol[i].columnname + "\");\n";
        strHighVolumeComp += selCol[i].xmltext;
        if (i<selCol.length-1) strHighVolume+=" && ";
      }
    }
    xmlDocument.setParameter("searchName", strHighVolume);
    xmlDocument.setParameter("searchVariables", strParamHighVolume);
    xmlDocument.setParameter("searchComparations", strHighVolumeComp);
    {
      StringBuffer fieldsRelationStructure = new StringBuffer();
      FieldsData[] fieldsDataSelect = null;
      fieldsDataSelect=copyarray(fieldsDataSelectAux);
      fieldsRelationStructure.append("strData.append(\"\\\"\").append(Replace.replace(Replace.replace(Replace.replace(data[contadorData].");
      fieldsRelationStructure.append(Sqlc.TransformaNombreColumna(keyColumnName));
      fieldsRelationStructure.append(", \"\\r\", \"\"), \"\\n\", \"<br>\"), \"\\\"\", \"\\\\\\\"\")).append(\"\\\"\");\n");
      for (int i=0; i<fieldsDataSelect.length; i++) {
        if (fieldsDataSelect[i].showinrelation.equals("Y") && fieldsDataSelect[i].isencrypted.equals("N") && (fieldsDataSelect[i].isdisplayed.equals("Y"))) {
          if (parentsFieldsData.length == 0 || !parentsFieldsData[0].name.equals(fieldsDataSelect[i].name)) {
            fieldsRelationStructure.append("strData.append(\",\");\n");
            fieldsRelationStructure.append("strData.append(\"\\\"\").append(Replace.replace(Replace.replace(Replace.replace(data[contadorData].");
            if ((fieldsDataSelect[i].reference.equals("17") || fieldsDataSelect[i].reference.equals("18") || fieldsDataSelect[i].reference.equals("19")) && fieldsDataSelect[i].isdisplayed.equals("Y")) {  // List
              fieldsDataSelect[i].name = fieldsDataSelect[i].name + "R"; //_REF
            } else if ((fieldsDataSelect[i].reference.equals("30") || fieldsDataSelect[i].reference.equals("800011") || fieldsDataSelect[i].reference.equals("31") || fieldsDataSelect[i].reference.equals("35") || fieldsDataSelect[i].reference.equals("25") || fieldsDataSelect[i].reference.equals("21") || fieldsDataSelect[i].reference.equals("32")) && fieldsDataSelect[i].isdisplayed.equals("Y")) {
              fieldsDataSelect[i].name = fieldsDataSelect[i].name + "R";
            }
            fieldsRelationStructure.append(Sqlc.TransformaNombreColumna(fieldsDataSelect[i].name));
            fieldsRelationStructure.append(", \"\\r\", \"\"), \"\\n\", \"<br>\"), \"\\\"\", \"\\\\\\\"\")).append(\"\\\"\");\n");
          }
        }
      }
      xmlDocument.setParameter("fieldsRelation", fieldsRelationStructure.toString());
    }
    if (WadUtility.findField(vecFields, "adClientId")) xmlDocument.setParameter("clientId", "data.adClientId");
    else xmlDocument.setParameter("clientId", "Utility.getContext(this, vars, \"#AD_Client_ID\", windowId)");
    
    if (WadUtility.findField(vecFields, "adOrgId")) xmlDocument.setParameter("orgId", "data.adOrgId");
    else xmlDocument.setParameter("orgId", "Utility.getContext(this, vars, \"#AD_Org_ID\", windowId)");
    
    //Parent field language
    if (parentsFieldsData!=null && parentsFieldsData.length>0) {
      Vector<Object> vecCounters2 = new Vector<Object>();
      Vector<Object> vecFields2 = new Vector<Object>();
      Vector<Object> vecTable2 = new Vector<Object>();
      Vector<Object> vecWhere2 = new Vector<Object>();
      Vector<Object> vecParameters2 = new Vector<Object>();
      Vector<Object> vecTableParameters2 = new Vector<Object>();
      vecCounters2.addElement("0");
      vecCounters2.addElement("0");
      WadUtility.columnIdentifier (pool, parentsFieldsData[0].tablename, true, parentsFieldsData[0], vecCounters2, true, vecFields2, vecTable2, vecWhere2, vecParameters2, vecTableParameters2, sqlDateFormat);
      
      xmlDocument.setParameter("parentLanguage", (vecParameters2.size()>0 || vecTableParameters2.size()>0)?", vars.getLanguage()":"");
    }
    FieldsData[] fieldsData=null;
    Vector<Object> vector = new Vector<Object>();
    boolean defaultValue;
    {
      Vector<Object> vecFieldsSelect = new Vector<Object>();
      FieldsData[] fieldsData1 = null;
      fieldsData1=copyarray(fieldsDataSelectAux);
      for (int i=0;i< fieldsData1.length; i++) {
        if (!fieldsData1[i].name.equalsIgnoreCase("Created") && !fieldsData1[i].name.equalsIgnoreCase("CreatedBy") && !fieldsData1[i].name.equalsIgnoreCase("Updated") && !fieldsData1[i].name.equalsIgnoreCase("UpdatedBy")) {
          fieldsData1[i].name = Sqlc.TransformaNombreColumna(fieldsData1[i].name);
          fieldsData1[i].columnname = fieldsData1[i].name;
          defaultValue=false;
          if (!fieldsData1[i].reference.equals("23") && !WadUtility.isDateTimeField(fieldsData1[i].reference) && !fieldsData1[i].reference.equals("20") && !WadUtility.isDecimalNumber(fieldsData1[i].reference) && !WadUtility.isQtyNumber(fieldsData1[i].reference) && !WadUtility.isPriceNumber(fieldsData1[i].reference) && !WadUtility.isIntegerNumber(fieldsData1[i].reference) && !WadUtility.isGeneralNumber(fieldsData1[i].reference) && WadUtility.columnRelationFormat(fieldsData1[i], false, MAX_COL_SIZE_RELATION)) vector.addElement(fieldsData1[i]);
          if (fieldsData1[i].reference.equals("20")) {
            fieldsData1[i].xmltext = ", \"N\"";
            defaultValue=true;
          } else {
            fieldsData1[i].xmltext = "";
          }

          if (fieldsData1[i].iskey.equals("Y")) {
            fieldsData1[i].xmltext = ", windowId + \"|" + fieldsData1[i].realname + "\"";
            fieldsData1[i].type = "RequestGlobalVariable";
          } else if (fieldsData1[i].issessionattr.equals("Y")) {
            fieldsData1[i].xmltext = ", windowId + \"|" + fieldsData1[i].realname + "\"";
            if (fieldsData1[i].reference.equals("20")) fieldsData1[i].xmltext += ", \"N\"";
            if (fieldsData1[i].required.equals("Y") && !fieldsData1[i].columnname.equalsIgnoreCase("Value") && !defaultValue) {
              if (fieldsData1[i].reference.equals("20")) fieldsData1[i].type = "RequiredInputGlobalVariable";
              else fieldsData1[i].type = "RequiredGlobalVariable";
            } else {
              if (fieldsData1[i].reference.equals("20")) fieldsData1[i].type = "RequiredInputGlobalVariable";
              else fieldsData1[i].type = "RequestGlobalVariable";
            }
          } else if (fieldsData1[i].required.equals("Y") && !fieldsData1[i].columnname.equalsIgnoreCase("Value") && !defaultValue) {
            fieldsData1[i].type = "RequiredStringParameter";
          }
          if (fieldsData1[i].iscolumnencrypted.equals("Y") && fieldsData1[i].isdesencryptable.equals("Y")) {
            fieldsData1[i].htmltext = "FormatUtilities.encryptDecrypt(";
            fieldsData1[i].htmltexttrl = ", true)";
          } else if (fieldsData1[i].iscolumnencrypted.equals("Y") && fieldsData1[i].isdesencryptable.equals("N")) {
            fieldsData1[i].htmltext = "FormatUtilities.sha1Base64(";
            fieldsData1[i].htmltexttrl = ")";
          }
          vecFieldsSelect.addElement(fieldsData1[i]);
          if ((WadUtility.isSearchType(fieldsData1[i].reference) || WadUtility.isSelectType(fieldsData1[i].reference)) && fieldsData1[i].isdisplayed.equals("Y")) {
            FieldsData fieldsData2 = null;
            fieldsData2=copyarrayElement(fieldsData1[i]);
            fieldsData2.name += "r";//(WadUtility.isSearchType(fieldsData1[i].reference)?"D":"r"); 
            fieldsData2.columnname += "_R";
            fieldsData2.type = "StringParameter";
            fieldsData2.xmltext = "";
            vecFieldsSelect.addElement(fieldsData2);
          }
        }
      }
      fieldsData = new FieldsData[vecFieldsSelect.size()];
      vecFieldsSelect.copyInto(fieldsData);
    }

    FieldsData[] fieldsTruncate = new FieldsData[vector.size()];
    vector.copyInto(fieldsTruncate);

    //Campos del Session actual
    //Fields of the current Session
    FieldsData[] fieldsSession = FieldsData.selectSession(pool, strTab);
    if (fieldsSession!=null) {
      for (int i=0;i< fieldsSession.length; i++) {
        fieldsSession[i].name = Sqlc.TransformaNombreColumna(fieldsSession[i].name);
        if (fieldsSession[i].reference.equals("20")) {
          fieldsSession[i].xmltext = ", \"N\"";
        } else {
          fieldsSession[i].xmltext = "";
        }
      }
    }

    //Fields of the parent Session
    FieldsData[] fieldsParentSession = null;
    FieldsData[] auxiliarPFields=null;
    if (parentTab!=-1) {
      xmlDocument.setParameter("parentClass", FormatUtilities.replace(allTabs[parentTab].tabname));
      fieldsParentSession = FieldsData.selectSession(pool, allTabs[parentTab].tabid);
      for (int i=0;i< fieldsParentSession.length; i++) {
        fieldsParentSession[i].name = Sqlc.TransformaNombreColumna(fieldsParentSession[i].name);
        if (fieldsParentSession[i].reference.equals("20")) {
          fieldsParentSession[i].xmltext = ", \"N\"";
        } else {
          fieldsParentSession[i].xmltext = "";
        }
      }
      //Auxiliary fields of the parent
      Vector<Object> vecAuxiliarPFields = new Vector<Object>();
      auxiliarPFields = FieldsData.selectAuxiliar(pool, "", allTabs[parentTab].tabid);
      if (auxiliarPFields!=null) {
        for (int i=0;i<auxiliarPFields.length;i++) {
          auxiliarPFields[i].columnname = Sqlc.TransformaNombreColumna(auxiliarPFields[i].columnname);
          if (auxiliarPFields[i].defaultvalue.toUpperCase().startsWith("@SQL=")) {
            auxiliarPFields[i].defaultvalue = FormatUtilities.replace(allTabs[parentTab].tabname) + "Data.selectAux" + auxiliarPFields[i].reference + "(this" + WadUtility.getWadContext(auxiliarPFields[i].defaultvalue, vecFields, vecAuxiliarPFields, parentsFieldsData, false, isSOTrx, strWindow) + ")";
          } else if (auxiliarPFields[i].defaultvalue.indexOf("@")!=-1) {
            auxiliarPFields[i].defaultvalue = WadUtility.getTextWadContext(auxiliarPFields[i].defaultvalue, vecFields, vecAuxiliarPFields, parentsFieldsData, false, isSOTrx, strWindow);
          } else {
            auxiliarPFields[i].defaultvalue = "\"" + auxiliarPFields[i].defaultvalue + "\"";
          }
          vecAuxiliarPFields.addElement(auxiliarPFields[i].name);
        }
      }
    } else {
      fieldsParentSession = FieldsData.set();
      auxiliarPFields = FieldsData.set();
    }

    
    /*FieldsData[] tables = FieldsData.selectTables(pool, strTab);
    if (tables!=null) {
      for (int i=0;i<tables.length;i++) {
        StringBuffer where = new StringBuffer();
        Vector<Object> vecFields1 = new Vector<Object>();
        Vector<Object> vecTables = new Vector<Object>();
        Vector<Object> vecWhere = new Vector<Object>();
        Vector<Object> vecParameters = new Vector<Object>();
        Vector<Object> vecTableParameters = new Vector<Object>();
        String translated = WadUtility.columnIdentifier(pool, tables[i].tablename, true, tables[i], 0, 0, true, vecFields1, vecTables, vecWhere, vecParameters, vecTableParameters, sqlDateFormat);
        where.append(tables[i].whereclause);
        if (!tables[i].columnname.equals("")) {
          //tables[i].referencevalue += "_" + tables[i].columnname;
          tables[i].tablename = "TableListVal";
          if (!where.toString().equals("")) where.append(" AND ");
          where.append(tables[i].defaultvalue);
        } else {
          tables[i].tablename = "TableList";
        }
        tables[i].whereclause = "";
        if (vecTableParameters.size()>0) tables[i].whereclause = ", vars.getLanguage()";
        tables[i].whereclause+=", Utility.getContext(this, vars, \"#User_Org\", windowId), Utility.getContext(this, vars, \"#User_Client\", windowId)";
        String table_Name = tables[i].nameref;
        tables[i].whereclause += WadUtility.getWadContext(where.toString(), vecFields, vecAuxiliarFields, parentsFieldsData, false, isSOTrx, strWindow);
        tables[i].xmltext = tables[i].whereclause;
        if (vecParameters.size()>0 && vecTableParameters.size()==0) tables[i].whereclause += ", vars.getLanguage()";
        tables[i].xmltext = tables[i].whereclause;
        tables[i].nameref = "data[0]." + Sqlc.TransformaNombreColumna(tables[i].name);
        tables[i].whereclause += ", data[0]." + Sqlc.TransformaNombreColumna(tables[i].name);
        tables[i].xmltext += ", data[0]." + Sqlc.TransformaNombreColumna(tables[i].name);
      }
    }*/

    /*FieldsData[] tableDir = FieldsData.selectTableDirs(pool, strTab);
    if (tableDir!=null) {
      for (int i=0;i<tableDir.length;i++) {
        String table_Name = tableDir[i].name.substring(0,tableDir[i].name.length()-3);
        Vector<Object> vecFields1 = new Vector<Object>();
        Vector<Object> vecTables = new Vector<Object>();
        Vector<Object> vecWhere = new Vector<Object>();
        Vector<Object> vecParameters = new Vector<Object>();
        Vector<Object> vecTableParameters = new Vector<Object>();
        String translated = WadUtility.columnIdentifier(pool, table_Name, true, tableDir[i], 0, 0, true, vecFields1, vecTables, vecWhere, vecParameters, vecTableParameters, sqlDateFormat);
        tableDir[i].whereclause = ((vecTableParameters.size()>0)?", vars.getLanguage()":"");
        tableDir[i].whereclause += ", Utility.getContext(this, vars, \"#User_Org\", windowId), Utility.getContext(this, vars, \"#User_Client\", windowId)";
        if (!tableDir[i].columnname.equals("")) {
          //tableDir[i].referencevalue += "_" + tableDir[i].columnname;
          tableDir[i].tablename = "TableDirVal";
          tableDir[i].whereclause += WadUtility.getWadContext(tableDir[i].defaultvalue, vecFields, vecAuxiliarFields, parentsFieldsData, false, isSOTrx, strWindow);
        } else {
          tableDir[i].tablename = "TableDir";
        }
        if (vecParameters.size()>0 && vecTableParameters.size()==0) tableDir[i].whereclause += ", vars.getLanguage()";
        tableDir[i].xmltext = tableDir[i].whereclause;
        tableDir[i].nameref = "data[0]." + Sqlc.TransformaNombreColumna(tableDir[i].name);
        tableDir[i].whereclause += ", data[0]." + Sqlc.TransformaNombreColumna(tableDir[i].name);
        tableDir[i].xmltext += ", data[0]." + Sqlc.TransformaNombreColumna(tableDir[i].name);
      }
    }*/
    
    if (fieldsSession!=null) {
      for (int i=0;i<fieldsSession.length;i++) {
        if (!fieldsSession[i].columnname.equals("")) {
          fieldsSession[i].referencevalue += "_" + fieldsSession[i].columnname;
          fieldsSession[i].tablename = "TableDirValData";
          fieldsSession[i].whereclause = ", Utility.getContext(this, vars, \"#User_Org\", windowId), Utility.getContext(this, vars, \"#User_Client\", windowId)";
          fieldsSession[i].whereclause += WadUtility.getWadContext(fieldsSession[i].defaultvalue, vecFields, vecAuxiliarFields, parentsFieldsData, false, isSOTrx, strWindow);
          fieldsSession[i].whereclause += ", data[0]." + Sqlc.TransformaNombreColumna(fieldsSession[i].name);
        }
      }
    }

    {
      FieldsData[] docsNoFields = FieldsData.selectDocumentsNo(pool, strTab);
      if (docsNoFields!=null) {
        String field="";
        for (int i=0;i<docsNoFields.length;i++) {
          docsNoFields[i].columnname = Sqlc.TransformaNombreColumna(docsNoFields[i].columnname);
          docsNoFields[i].defaultvalue = "Utility.getDocumentNo(this, vars, windowId, \"" + docsNoFields[i].nameref + "\", ";
          docsNoFields[i].realname = "Utility.getDocumentNo(this, vars, windowId, \"" + docsNoFields[i].nameref + "\", ";
          field=WadUtility.findField(pool, allfields, auxiliarsData, "C_DocTypeTarget_ID");
          if (!field.equals("")) {
            docsNoFields[i].defaultvalue += "data[0]." + Sqlc.TransformaNombreColumna(field);
            docsNoFields[i].realname += "data." + Sqlc.TransformaNombreColumna(field);
          } else {
            docsNoFields[i].defaultvalue += "\"\"";
            docsNoFields[i].realname += "\"\"";
          }
          docsNoFields[i].defaultvalue += ", ";
          docsNoFields[i].realname += ", ";
          field=WadUtility.findField(pool, allfields, auxiliarsData, "C_DocType_ID");
          if (!field.equals("")) {
            docsNoFields[i].defaultvalue += "data[0]." + Sqlc.TransformaNombreColumna(field);
            docsNoFields[i].realname += "data." + Sqlc.TransformaNombreColumna(field);
          } else {
            docsNoFields[i].defaultvalue += "\"\"";
            docsNoFields[i].realname += "\"\"";
          }
          docsNoFields[i].defaultvalue += ", false, false)";
          docsNoFields[i].realname += ", false, true)";
        }
      }
      xmlDocument.setData("structure12", docsNoFields);
      xmlDocument.setData("structure13", docsNoFields);
      {
        FieldsData[] docsIdentify = FieldsData.selectIdentify(pool, strTab);
        if (docsIdentify!=null) {
          for (int i=0;i<docsIdentify.length;i++) {
            if (docsNoFields==null || docsNoFields.length == 0) {
              docsIdentify[i].realname = "Utility.getDocumentNo(this, vars.getClient(), \"" + docsIdentify[i].nameref + "\", true)";
              if (docsIdentify[i].issessionattr.equals("Y")) docsIdentify[i].realname += ";\nvars.setSessionValue(windowId + \"|" + docsIdentify[i].columnname + "\", data." + Sqlc.TransformaNombreColumna(docsIdentify[i].columnname) + ")";
            } else {
              docsIdentify[i].realname = "data." + docsNoFields[0].columnname;
            }
            docsIdentify[i].columnname = Sqlc.TransformaNombreColumna(docsIdentify[i].columnname);
          }
        }
        xmlDocument.setData("structure23", docsIdentify);
      }
    }

    xmlDocument.setData("structure1", fieldsData);
    xmlDocument.setData("structure2", fieldsTruncate);
    /*{
      FieldsData[] fieldLists = FieldsData.selectLists(pool, strTab);
      if (fieldLists!=null && fieldLists.length>0) {
        for (int h=0;h<fieldLists.length;h++) {
          fieldLists[h].nameref = "data[0]." + Sqlc.TransformaNombreColumna(fieldLists[h].nameref);
        }
      }
      xmlDocument.setData("structure4", fieldLists);
    }*/
    //xmlDocument.setData("structure5", tables);
    //xmlDocument.setData("structure6", tableDir);
    xmlDocument.setData("structure7", auxiliarFields);
    xmlDocument.setData("structure27", auxiliarFields);
    xmlDocument.setData("structure8", fieldsParentSession);
    xmlDocument.setData("structure9", fieldsSession);
    xmlDocument.setData("structure10", auxiliarFields);
    xmlDocument.setData("structure11", auxiliarPFields);
    {
      ActionButtonRelationData[] abrd = WadActionButton.buildActionButtonCall(pool, strTab, tabName, keyColumnName, isSOTrx, strWindow);
      xmlDocument.setData("structure14", abrd);
      xmlDocument.setData("structure15", abrd);
      xmlDocument.setData("structure16", abrd);
    }

    xmlDocument.setData("structure18", selCol);
    xmlDocument.setData("structure20", selCol);
    xmlDocument.setData("structure22", selCol);
    xmlDocument.setData("structure24", selCol);
    xmlDocument.setData("structure25", selCol);
    xmlDocument.setData("structure26", selCol);

    //Encrypted Fields
    {
      FieldsData[] encryptedData = FieldsData.selectEncrypted(pool, strTab);
      if (encryptedData!=null && encryptedData.length>0) {
        for (int g=0;g<encryptedData.length;g++) {
          encryptedData[g].realname = Sqlc.TransformaNombreColumna(encryptedData[g].realname);
          encryptedData[g].name = FormatUtilities.replace(encryptedData[g].name);
          if (encryptedData[g].isdesencryptable.equals("Y")) {
            encryptedData[g].xmlFormat = "encryptDecrypt";
            encryptedData[g].htmltext = ", true";
          } else {
            encryptedData[g].xmlFormat = "sha1Base64";
            encryptedData[g].htmltext = "";
          }
        }
      }
      xmlDocument.setData("structure32", encryptedData);
      xmlDocument.setData("structure33", encryptedData);
      xmlDocument.setData("structure34", encryptedData);
      xmlDocument.setData("structure35", encryptedData);
    }

    //Button Fields
    {
      FieldsData[] buttonData = FieldsData.selectButton(pool, strTab);
      if (buttonData!=null && buttonData.length>0) {
        for (int g=0;g<buttonData.length;g++) {
          buttonData[g].realname = Sqlc.TransformaNombreColumna(buttonData[g].realname);
        }
      }
      xmlDocument.setData("structure36", buttonData);
    }

    StringBuffer strDefaultValues = new StringBuffer();
    FieldsData sfd[] = FieldsData.selectDefaultValue(pool, "", strTab);
    int isSelect=0;
    for (int i=0;i< sfd.length; i++) {
      if (!hasParentsFields || !parentsFieldsData[0].name.equalsIgnoreCase(sfd[i].columnname)) {
        if (sfd[i].defaultvalue.toUpperCase().startsWith("@SQL=")) {
          sfd[i].defaultvalue = tabName + "Data.selectDef" + sfd[i].reference + "(this" + WadUtility.getWadContext(sfd[i].defaultvalue, vecFields, vecAuxiliarFields, parentsFieldsData, true, isSOTrx, strWindow) + ")";
        } else if (sfd[i].columnname.equalsIgnoreCase("isActive")) {
          sfd[i].defaultvalue="\"Y\"";
        } else if (sfd[i].accesslevel.equals("4") && (sfd[i].columnname.equalsIgnoreCase("AD_CLIENT_ID") || sfd[i].columnname.equalsIgnoreCase("AD_ORG_ID"))) {
          sfd[i].defaultvalue = "\"0\"";
        } else if (sfd[i].accesslevel.equals("6") && sfd[i].columnname.equalsIgnoreCase("AD_ORG_ID")) {
          sfd[i].defaultvalue = "\"0\"";
        } else {
          sfd[i].defaultvalue = "Utility.getDefault(this, vars, \"" + sfd[i].columnname + "\", \"" + sfd[i].defaultvalue + "\", \"" + strWindow + "\", \"" + WadUtility.getWadDefaultValue(sfd[i]) + "\")";
        }
        if (!strDefaultValues.toString().equals("") || hasParentsFields) strDefaultValues.append(", ");
        strDefaultValues.append(sfd[i].defaultvalue);
      } else {
        sfd[i].defaultvalue = "strP" + sfd[i].columnname;
      }
      if ((sfd[i].referencevalue.equals("30") || sfd[i].referencevalue.equals("31") || sfd[i].referencevalue.equals("35") || sfd[i].referencevalue.equals("25") || sfd[i].reference.equals("800011")) && sfd[i].isdisplayed.equals("Y")) strDefaultValues.append(", " + tabName + "Data.selectDef" + sfd[i].reference + "_" + (isSelect++) + "(this, " + sfd[i].defaultvalue + ")");
      else if (sfd[i].referencevalue.equals("28") && sfd[i].isdisplayed.equals("Y") && !sfd[i].type.equals("")) strDefaultValues.append(", (vars.getLanguage().equals(\"en_US\")?ListData.selectName(this, \"").append(sfd[i].type).append("\", ").append(sfd[i].defaultvalue).append("):ListData.selectNameTrl(this, vars.getLanguage(), \"").append(sfd[i].type).append("\", ").append(sfd[i].defaultvalue).append("))");
      else if (sfd[i].referencevalue.equals("21") && sfd[i].isdisplayed.equals("Y")) strDefaultValues.append(", LocationSearchData.locationAddress(this, " + sfd[i].defaultvalue + ")");
      else if (sfd[i].referencevalue.equals("32") && sfd[i].isdisplayed.equals("Y")) strDefaultValues.append(", " + tabName + "Data.selectDef" + sfd[i].reference + "_" + (isSelect++) + "(this, " + sfd[i].defaultvalue + ")");
    }

    StringBuffer controlsJavaSource = new StringBuffer();
    for (int i=0;i<allfields.length;i++) {
      WADControl auxControl = null;
      try {
        auxControl = WadUtility.getControl(pool, allfields[i], strReadOnly, tabName, "", xmlEngine, false, false);
      } catch (Exception ex) {
        throw new ServletException(ex);
      }
      controlsJavaSource.append(auxControl.toJava()).append((auxControl.toJava().equals("")?"":"\n"));
    }
    xmlDocument.setParameter("controlsJavaCode", controlsJavaSource.toString());
    xmlDocument.setParameter("defaultValues", strDefaultValues.toString());
    WadUtility.writeFile(fileDir, tabName + ".java", xmlDocument.print());
  }

  private String generateStaticWhere(String strWhere, Vector<Object> vecParameters) {
    StringBuffer result = new StringBuffer();
    if (strWhere==null || strWhere.equals("")) return strWhere;
    int pos = strWhere.indexOf("?");
    int questNumber = 0;
    while (pos!=-1) {
      result.append(strWhere.substring(0, pos));
      strWhere = strWhere.substring(pos+1);
      String strParam = (String)vecParameters.elementAt(questNumber);
      strParam = strParam.substring(17, strParam.lastIndexOf("\""));
      questNumber++;
      if (strParam.equalsIgnoreCase("paramLanguage")) result.append(" '\" + vars.getLanguage() + \"' ");
      else result.append(" '\" + Utility.getContext(this, vars, \"" + strParam + "\", windowId) + \"' ");
      pos = strWhere.indexOf("?");
    };
    result.append(strWhere);
    return result.toString();
  }


  private void processTabXSQLSortTab(FieldsData[] parentsFieldsData, File fileDir, String strTab, String tabName, String tableName, String windowName, String keyColumnName, String strColumnSortOrderId, String strColumnSortYNId, Vector<Object> vecParametersTop, Vector<Object> vecTableParametersTop) throws ServletException, IOException {
    log4j.debug("Processing Sort Tab xsql: " + strTab + ", " + tabName);
    XmlDocument xmlDocumentXsql;
    String[] discard = {"", ""};
    if (parentsFieldsData==null || parentsFieldsData.length == 0) discard[0] = "parent";  // remove the parent tags
    xmlDocumentXsql = xmlEngine.readXmlTemplate("org/openbravo/wad/datasourceSortTab", discard).createXmlDocument();
    
    xmlDocumentXsql.setParameter("class", tabName + "Data");
    xmlDocumentXsql.setParameter("package", "org.openbravo.erpWindows." + windowName);
    xmlDocumentXsql.setParameter("table", tableName);
    xmlDocumentXsql.setParameter("key", tableName + "." + keyColumnName);
    xmlDocumentXsql.setParameter("SortConditionField", FieldsData.columnName(pool, strColumnSortYNId));
    String strSortField = FieldsData.columnName(pool, strColumnSortOrderId);
    xmlDocumentXsql.setParameter("SortField", strSortField);
    xmlDocumentXsql.setParameter("SortFieldInp", Sqlc.TransformaNombreColumna(strSortField));
    if (parentsFieldsData.length > 0) {
      xmlDocumentXsql.setParameter("keyParent", tableName + "." + parentsFieldsData[0].name);
    }
    xmlDocumentXsql.setParameter("paramKey", Sqlc.TransformaNombreColumna(keyColumnName));
    if (parentsFieldsData.length > 0) {
      xmlDocumentXsql.setParameter("paramKeyParent", Sqlc.TransformaNombreColumna(parentsFieldsData[0].name));
    }
    String strOrder = " ORDER BY " + tableName + "." + strSortField;

    String strFields = "";
    String strTables = "";
    String strWhere = "";
    {
      Vector<Object> vecCounters = new Vector<Object>();
      Vector<Object> vecFields = new Vector<Object>();
      Vector<Object> vecTable = new Vector<Object>();
      Vector<Object> vecWhere = new Vector<Object>();
      FieldsData[] data = FieldsData.identifierColumns(pool, tableName);
      log4j.debug("Total Identifiers for " + tableName + ": " + data.length);
      if (data==null) strFields = "''";
      vecCounters.addElement("0");
      vecCounters.addElement("0");
      for (int i=0;i<data.length;i++) {
        if (i!=0) strFields += " || ' - ' || ";
        strFields += WadUtility.columnIdentifier(pool, tableName, true, data[i], vecCounters, false, vecFields, vecTable, vecWhere, vecParametersTop, vecTableParametersTop, sqlDateFormat);
      }
      for (int i=0;i<vecTable.size();i++) {
        String strAux = (String) vecTable.elementAt(i);
        strTables += (strAux.trim().toLowerCase().startsWith("left join")?" ":", ") + strAux;
      }
      for (int i=0;i<vecWhere.size();i++) {
        strWhere += "\n AND " + vecWhere.elementAt(i).toString();
      }
    }

    xmlDocumentXsql.setParameter("fields", strFields);

    //Relation select
    xmlDocumentXsql.setParameter("tables", strTables);
    xmlDocumentXsql.setParameter("where", strWhere);
    xmlDocumentXsql.setParameter("order", strOrder);
    StringBuffer strParameters = new StringBuffer();
    for (int i=0;i<vecTableParametersTop.size();i++) {
      strParameters.append(vecTableParametersTop.elementAt(i).toString()).append("\n");
    }
    for (int i=0;i<vecParametersTop.size();i++) {
      strParameters.append(vecParametersTop.elementAt(i).toString()).append("\n");
    }
    xmlDocumentXsql.setParameter("parameters", strParameters.toString());
    //Parent field
    if (parentsFieldsData!=null && parentsFieldsData.length>0) {
      Vector<Object> vecCounters = new Vector<Object>();
      Vector<Object> vecFields = new Vector<Object>();
      Vector<Object> vecTable = new Vector<Object>();
      Vector<Object> vecWhere = new Vector<Object>();
      Vector<Object> vecParameters = new Vector<Object>();
      Vector<Object> vecTableParameters = new Vector<Object>();
      vecCounters.addElement("0");
      vecCounters.addElement("0");
      String strText = WadUtility.columnIdentifier(pool, parentsFieldsData[0].tablename, true, parentsFieldsData[0], vecCounters, false, vecFields, vecTable, vecWhere, vecParameters, vecTableParameters, sqlDateFormat);
      FieldsData[] fieldsParent = new FieldsData[1];
      fieldsParent[0] = new FieldsData();
      fieldsParent[0].defaultvalue = "SELECT (" + strText + ") AS NAME FROM ";
      fieldsParent[0].defaultvalue += parentsFieldsData[0].tablename;
      for (int s=0;s<vecTable.size();s++) {
        String strAux = (String) vecTable.elementAt(s);
        fieldsParent[0].defaultvalue += (strAux.trim().toLowerCase().startsWith("left join")?" ":", ") + strAux;
      }
      fieldsParent[0].defaultvalue += " WHERE " + parentsFieldsData[0].tablename + "." + parentsFieldsData[0].name + " = ? ";
      for (int s=0;s<vecWhere.size();s++) {
        fieldsParent[0].defaultvalue += " AND " + vecWhere.elementAt(s).toString();
      }
      fieldsParent[0].whereclause = "";
      for (int s=0;s<vecTableParameters.size();s++) {
        fieldsParent[0].whereclause += vecTableParameters.elementAt(s).toString() + "\n";
      }
      fieldsParent[0].whereclause += "<Parameter name=\"" + Sqlc.TransformaNombreColumna(parentsFieldsData[0].name) + "\"/>\n";
      for (int s=0;s<vecParameters.size();s++) {
        fieldsParent[0].whereclause += vecParameters.elementAt(s).toString() + "\n";
      }
      xmlDocumentXsql.setData("structure14", fieldsParent);
    } else {
      xmlDocumentXsql.setData("structure14", null);
    }
    //Parent field translated
    if (parentsFieldsData!=null && parentsFieldsData.length>0) {
      Vector<Object> vecCounters = new Vector<Object>();
      Vector<Object> vecFields = new Vector<Object>();
      Vector<Object> vecTable = new Vector<Object>();
      Vector<Object> vecWhere = new Vector<Object>();
      Vector<Object> vecParameters = new Vector<Object>();
      Vector<Object> vecTableParameters = new Vector<Object>();
      vecCounters.addElement("0");
      vecCounters.addElement("0");
      String strText = WadUtility.columnIdentifier (pool, parentsFieldsData[0].tablename, true, parentsFieldsData[0], vecCounters, true, vecFields, vecTable, vecWhere, vecParameters, vecTableParameters, sqlDateFormat);
      FieldsData[] fieldsParent = new FieldsData[1];
      fieldsParent[0] = new FieldsData();
      fieldsParent[0].defaultvalue = "SELECT (" + strText + ") AS NAME FROM " + parentsFieldsData[0].tablename;
      for (int s=0;s<vecTable.size();s++) {
        String strAux = (String) vecTable.elementAt(s);
        fieldsParent[0].defaultvalue += (strAux.trim().toLowerCase().startsWith("left join")?" ":", ") + strAux;
      }
      fieldsParent[0].defaultvalue += " WHERE " + parentsFieldsData[0].tablename + "." + parentsFieldsData[0].name + " = ? ";
      for (int s=0;s<vecWhere.size();s++) {
        fieldsParent[0].defaultvalue += " AND " + vecWhere.elementAt(s).toString();
      }
      fieldsParent[0].whereclause = "";
      for (int s=0;s<vecTableParameters.size();s++) {
        fieldsParent[0].whereclause += vecTableParameters.elementAt(s).toString() + "\n";
      }
      fieldsParent[0].whereclause += "<Parameter name=\"" + Sqlc.TransformaNombreColumna(parentsFieldsData[0].name) + "\"/>\n";
      for (int s=0;s<vecParameters.size();s++) {
        fieldsParent[0].whereclause += vecParameters.elementAt(s).toString() + "\n";
      }
      xmlDocumentXsql.setData("structure15", fieldsParent);
    } else {
      xmlDocumentXsql.setData("structure15", null);
    }
    WadUtility.writeFile(fileDir, tabName + "_data.xsql", "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" + xmlDocumentXsql.print());
  }


  private void processTabXSQL(FieldsData[] parentsFieldsData, File fileDir, String strTab, String tabName, String tableName, String windowName, String keyColumnName, String strFields, String strTables, String strOrder, String strWhere, Vector<Object> vecParametersTop, String strFilter, EditionFieldsData[] selCol, String tablevel, String windowType, Vector<Object> vecTableParametersTop, FieldsData[] fieldsDataSelectAux) throws ServletException, IOException {
    log4j.debug("Procesig xsql: " + strTab + ", " + tabName);
    XmlDocument xmlDocumentXsql;
    String[] discard = {"", "", "", "", "", "", ""};
    if (parentsFieldsData==null || parentsFieldsData.length == 0) discard[0] = "parent";  // remove the parent tags
    if (tableName.toUpperCase().endsWith("_ACCESS")) {
      discard[6] = "client";
      discard[1] = "org";
    } //else if (tableName.toUpperCase().startsWith("M_PRODUCT") || tableName.toUpperCase().startsWith("C_BP") || tableName.toUpperCase().startsWith("AD_ORG")) discard[1] = "org";
    if (selCol==null || selCol.length==0) {
      discard[2] = "sectionHighVolume";
      discard[3] = "sectionHighVolume1";
    }
    if (!(windowType.equalsIgnoreCase("T") && tablevel.equals("0"))) discard[4] = "sectionTransactional";
    if (strFilter.trim().equals("")) discard[5] = "sectionFilter";
    xmlDocumentXsql = xmlEngine.readXmlTemplate("org/openbravo/wad/datasource", discard).createXmlDocument();
    
    xmlDocumentXsql.setParameter("class", tabName + "Data");
    xmlDocumentXsql.setParameter("package", "org.openbravo.erpWindows." + windowName);
    xmlDocumentXsql.setParameter("table", tableName);
    xmlDocumentXsql.setParameter("key", tableName + "." + keyColumnName);
    if (parentsFieldsData.length > 0) {
      xmlDocumentXsql.setParameter("keyParent", tableName + "." + parentsFieldsData[0].name);
    }
    xmlDocumentXsql.setParameter("paramKey", Sqlc.TransformaNombreColumna(keyColumnName));
    if (parentsFieldsData.length > 0) {
      xmlDocumentXsql.setParameter("paramKeyParent", Sqlc.TransformaNombreColumna(parentsFieldsData[0].name));
    }

    xmlDocumentXsql.setParameter("fields", strFields);
    
    //Relation select
    xmlDocumentXsql.setParameter("tables", strTables);
    xmlDocumentXsql.setParameter("where", strWhere);
    xmlDocumentXsql.setParameter("filter", strFilter);
    xmlDocumentXsql.setParameter("order", strOrder);
    StringBuffer strParameters = new StringBuffer();
    for (int i=0;i<vecTableParametersTop.size();i++) {
      strParameters.append(vecTableParametersTop.elementAt(i).toString()).append("\n");
    }
    for (int i=0;i<vecParametersTop.size();i++) {
      strParameters.append(vecParametersTop.elementAt(i).toString()).append("\n");
    }
    xmlDocumentXsql.setParameter("parameters", strParameters.toString());
    //Parent field
    if (parentsFieldsData!=null && parentsFieldsData.length>0) {
      Vector<Object> vecCounters = new Vector<Object>();
      Vector<Object> vecFields = new Vector<Object>();
      Vector<Object> vecTable = new Vector<Object>();
      Vector<Object> vecWhere = new Vector<Object>();
      Vector<Object> vecParameters = new Vector<Object>();
      Vector<Object> vecTableParameters = new Vector<Object>();
      vecCounters.addElement("0");
      vecCounters.addElement("0");
      String strText = WadUtility.columnIdentifier(pool, parentsFieldsData[0].tablename, true, parentsFieldsData[0], vecCounters, false, vecFields, vecTable, vecWhere, vecParameters, vecTableParameters, sqlDateFormat);
      FieldsData[] fieldsParent = new FieldsData[1];
      fieldsParent[0] = new FieldsData();
      fieldsParent[0].defaultvalue = "SELECT (" + strText + ") AS NAME FROM ";
      fieldsParent[0].defaultvalue += parentsFieldsData[0].tablename;
      for (int s=0;s<vecTable.size();s++) {
        String strAux = (String) vecTable.elementAt(s);
        fieldsParent[0].defaultvalue += (strAux.trim().toLowerCase().startsWith("left join")?" ":", ") + strAux;
      }
      fieldsParent[0].defaultvalue += " WHERE " + parentsFieldsData[0].tablename + "." + parentsFieldsData[0].name + " = ? ";
      for (int s=0;s<vecWhere.size();s++) {
        fieldsParent[0].defaultvalue += " AND " + vecWhere.elementAt(s).toString();
      }
      fieldsParent[0].whereclause = "";
      for (int s=0;s<vecTableParameters.size();s++) {
        fieldsParent[0].whereclause += vecTableParameters.elementAt(s).toString() + "\n";
      }
      fieldsParent[0].whereclause += "<Parameter name=\"" + Sqlc.TransformaNombreColumna(parentsFieldsData[0].name) + "\"/>\n";
      for (int s=0;s<vecParameters.size();s++) {
        fieldsParent[0].whereclause += vecParameters.elementAt(s).toString() + "\n";
      }
      xmlDocumentXsql.setData("structure14", fieldsParent);
    } else {
      xmlDocumentXsql.setData("structure14", null);
    }
    //Parent field translated
    if (parentsFieldsData!=null && parentsFieldsData.length>0) {
      Vector<Object> vecCounters = new Vector<Object>();
      Vector<Object> vecFields = new Vector<Object>();
      Vector<Object> vecTable = new Vector<Object>();
      Vector<Object> vecWhere = new Vector<Object>();
      Vector<Object> vecParameters = new Vector<Object>();
      Vector<Object> vecTableParameters = new Vector<Object>();
      vecCounters.addElement("0");
      vecCounters.addElement("0");
      String strText = WadUtility.columnIdentifier (pool, parentsFieldsData[0].tablename, true, parentsFieldsData[0], vecCounters, true, vecFields, vecTable, vecWhere, vecParameters, vecTableParameters, sqlDateFormat);
      FieldsData[] fieldsParent = new FieldsData[1];
      fieldsParent[0] = new FieldsData();
      fieldsParent[0].defaultvalue = "SELECT (" + strText + ") AS NAME FROM " + parentsFieldsData[0].tablename;
      for (int s=0;s<vecTable.size();s++) {
        String strAux = (String) vecTable.elementAt(s);
        fieldsParent[0].defaultvalue += (strAux.trim().toLowerCase().startsWith("left join")?" ":", ") + strAux;
      }
      fieldsParent[0].defaultvalue += " WHERE " + parentsFieldsData[0].tablename + "." + parentsFieldsData[0].name + " = ? ";
      for (int s=0;s<vecWhere.size();s++) {
        fieldsParent[0].defaultvalue += " AND " + vecWhere.elementAt(s).toString();
      }
      fieldsParent[0].whereclause = "";
      for (int s=0;s<vecTableParameters.size();s++) {
        fieldsParent[0].whereclause += vecTableParameters.elementAt(s).toString() + "\n";
      }
      fieldsParent[0].whereclause += "<Parameter name=\"" + Sqlc.TransformaNombreColumna(parentsFieldsData[0].name) + "\"/>\n";
      for (int s=0;s<vecParameters.size();s++) {
        fieldsParent[0].whereclause += vecParameters.elementAt(s).toString() + "\n";
      }
      xmlDocumentXsql.setData("structure15", fieldsParent);
    } else {
      xmlDocumentXsql.setData("structure15", null);
    }
    
    //Auxiliar Fields
    {
      FieldsData fieldsAux[] = FieldsData.selectAuxiliar(pool, "@SQL=", strTab);
      for (int i=0;i< fieldsAux.length; i++) {
        Vector<Object> vecParametros = new Vector<Object>();
        fieldsAux[i].defaultvalue = WadUtility.getSQLWadContext(fieldsAux[i].defaultvalue, vecParametros);
        StringBuffer parametros = new StringBuffer();
        for (Enumeration e = vecParametros.elements() ; e.hasMoreElements() ;) {
          String paramsElement = (String)e.nextElement();
          parametros.append("\n" + paramsElement);
        }
        fieldsAux[i].whereclause = parametros.toString();
      }
      xmlDocumentXsql.setData("structure9", fieldsAux);
    }
    //Default Fields
    {
      FieldsData fieldsDef[] = FieldsData.selectDefaultValue(pool, "", strTab);
      Vector<Object> v = new Vector<Object>();
      int itable=0;
      for (int i=0;i< fieldsDef.length; i++) {
        Vector<Object> vecParametros = new Vector<Object>();
        if (fieldsDef[i].defaultvalue.startsWith("@SQL=")) {
          fieldsDef[i].defaultvalue = WadUtility.getSQLWadContext(fieldsDef[i].defaultvalue, vecParametros);
          StringBuffer parametros = new StringBuffer();
          for (Enumeration e = vecParametros.elements() ; e.hasMoreElements() ;) {
            String paramsElement = (String)e.nextElement();
            parametros.append("\n" + paramsElement);
          }
          fieldsDef[i].whereclause = parametros.toString();
          v.addElement(fieldsDef[i]);
        }
        if ((fieldsDef[i].referencevalue.equals("30") || fieldsDef[i].referencevalue.equals("31") || fieldsDef[i].referencevalue.equals("35") || fieldsDef[i].reference.equals("800011") || fieldsDef[i].referencevalue.equals("25")) && fieldsDef[i].isdisplayed.equals("Y")) {
          FieldsData fd = new FieldsData();
          fd.reference = fieldsDef[i].reference + "_" + (itable++);
          fd.name = fieldsDef[i].columnname + "R";
          String tableN = "";
          EditionFieldsData[] dataSearchs = null;
          if (fieldsDef[i].referencevalue.equals("30")) dataSearchs = EditionFieldsData.selectSearchs(pool, "", fieldsDef[i].type);
          if (dataSearchs==null || dataSearchs.length==0) {
            if (fieldsDef[i].referencevalue.equals("25")) tableN = "C_ValidCombination";
            else if (fieldsDef[i].referencevalue.equals("31")) tableN = "M_Locator";
            else if (fieldsDef[i].referencevalue.equals("800011")) tableN = "M_Product";
            else tableN = fieldsDef[i].name.substring(0, fieldsDef[i].name.length()-3);
            if (fieldsDef[i].referencevalue.equals("25")) fieldsDef[i].name = "C_ValidCombination_ID";
            else if (fieldsDef[i].referencevalue.equals("31")) fieldsDef[i].name = "M_Locator_ID";
            else if (fieldsDef[i].referencevalue.equals("800011")) fieldsDef[i].name = "M_Product_ID";
          } else {
            tableN = dataSearchs[0].reference;
            fieldsDef[i].name = dataSearchs[0].columnname;
          }
          Vector<Object> vecFields2 = new Vector<Object>();
          Vector<Object> vecTables2 = new Vector<Object>();
          Vector<Object> vecWhere2 = new Vector<Object>();
          int itable2=0;
          vecTables2.addElement(tableN + " table1");
          itable2 = fieldsOfSearch2(tableN, fieldsDef[i].name, fieldsDef[i].required, vecFields2, vecTables2, vecWhere2, itable2, fieldsDef[i].referencevalue, fieldsDef[i].type);
          StringBuffer strFields2 = new StringBuffer();
          strFields2.append(" ( ");
          boolean boolFirst = true;
          for (Enumeration e = vecFields2.elements() ; e.hasMoreElements() ;) {
            String tableField = (String)e.nextElement();
            log4j.debug("  field: " + tableField);
            if (boolFirst) {
              boolFirst = false;
            } else {
              strFields2.append(" || ' - ' || ");
            }
            strFields2.append(tableField).append(" ");
          }
          strFields2.append(") as ").append(fieldsDef[i].columnname);
          StringBuffer fields = new StringBuffer();
          fields.append("SELECT ").append(strFields2);
          fields.append(" FROM ");
          for (int j=0;j<vecTables2.size();j++) {
            fields.append(vecTables2.elementAt(j));
          }
          fields.append(" WHERE table1.isActive='Y'");
          for (int j=0;j<vecWhere2.size();j++) {
            fields.append(vecWhere2.elementAt(j));
          }
          fields.append(" AND table1." + fieldsDef[i].name + " = ? ");
          fd.defaultvalue=fields.toString();
          fd.whereclause = "<Parameter name=\"" + fd.name + "\"/>";
          v.addElement(fd);
        } else if (fieldsDef[i].referencevalue.equals("32") && fieldsDef[i].isdisplayed.equals("Y")) {
          FieldsData fd = new FieldsData();
          fd.reference = fieldsDef[i].reference + "_" + (itable++);
          fd.name = fieldsDef[i].columnname + "R";
          String tableN = "AD_Image";
          fieldsDef[i].name = fieldsDef[i].name;
          Vector<Object> vecTables2 = new Vector<Object>();
          Vector<Object> vecWhere2 = new Vector<Object>();
          vecTables2.addElement(tableN + " table1");
          StringBuffer strFields2 = new StringBuffer();
          strFields2.append(" ( table1.ImageURL ) AS ").append(fieldsDef[i].columnname);
          StringBuffer fields = new StringBuffer();
          fields.append("SELECT ").append(strFields2);
          fields.append(" FROM ");
          for (int j=0;j<vecTables2.size();j++) {
            fields.append(vecTables2.elementAt(j));
          }
          fields.append(" WHERE table1.isActive='Y'");
          for (int j=0;j<vecWhere2.size();j++) {
            fields.append(vecWhere2.elementAt(j));
          }
          fields.append(" AND table1." + fieldsDef[i].name + " = ? ");
          fd.defaultvalue=fields.toString();
          fd.whereclause = "<Parameter name=\"" + fd.name + "\"/>";
          v.addElement(fd);
        }
      }
      FieldsData[] fd = new FieldsData[v.size()];
      v.copyInto(fd);
      xmlDocumentXsql.setData("structure10", fd);
    }
    {
      ProcessRelationData[] data = ProcessRelationData.selectXSQL(pool, strTab);
      if (data!=null) {
        for (int i=0;i<data.length;i++) {
          String tableN = "";
          if (data[i].adReferenceId.equals("28")) tableN = "C_ValidCombination";
          else if (data[i].adReferenceId.equals("31")) tableN = "M_Locator";
          else tableN = data[i].name.substring(0, data[i].searchname.length()-3);
          String strName = "";
          if (data[i].adReferenceId.equals("28")) strName = "C_ValidCombination_ID";
          else if (data[i].adReferenceId.equals("31")) strName = "M_Locator_ID";
          else strName = data[i].searchname;
          String strColumnName = FieldsData.columnIdentifier(pool, tableN);
          StringBuffer fields = new StringBuffer();
          fields.append("SELECT " + strColumnName);
          fields.append(" FROM " + tableN);
          fields.append(" WHERE isActive='Y'");
          fields.append(" AND " + strName + " = ? ");
          data[i].whereclause=fields.toString();
          data[i].name = FormatUtilities.replace(data[i].name);
        }
      }
      xmlDocumentXsql.setData("structure12", data);
    }
    //SQLs of the defaultvalue of the parameter of the tab-associated processes
    {
      ProcessRelationData fieldsAux[] = ProcessRelationData.selectXSQLParams(pool, strTab);
      if (fieldsAux!=null && fieldsAux.length>0) {
        for (int i=0;i< fieldsAux.length; i++) {
          Vector<Object> vecParametros = new Vector<Object>();
          fieldsAux[i].reference = fieldsAux[i].adProcessId + "_" + FormatUtilities.replace(fieldsAux[i].columnname);
          fieldsAux[i].defaultvalue = WadUtility.getSQLWadContext(fieldsAux[i].defaultvalue, vecParametros);
          StringBuffer parametros = new StringBuffer();
          for (Enumeration e = vecParametros.elements() ; e.hasMoreElements() ;) {
            String paramsElement = (String)e.nextElement();
            parametros.append("\n" + paramsElement);
          }
          fieldsAux[i].whereclause = parametros.toString();
        }
      }
      xmlDocumentXsql.setData("structure16", fieldsAux);
    }
    //Update
    {
      FieldsData fieldsDataUpdate[] = FieldsData.selectUpdatables(pool, strTab);
      for (int i=0;i< fieldsDataUpdate.length; i++) { // *** i=1?
        fieldsDataUpdate[i].name =   ((i>0)?", ":"") + fieldsDataUpdate[i].name;
        if (WadUtility.isTimeField(fieldsDataUpdate[i].reference)) fieldsDataUpdate[i].xmlFormat = "TO_DATE(?,'HH24:MI:SS')";
        else fieldsDataUpdate[i].xmlFormat = WadUtility.sqlCasting(pool, fieldsDataUpdate[i].reference, fieldsDataUpdate[i].referencevalue) + "(?)";
      }
      xmlDocumentXsql.setData("structure3", fieldsDataUpdate);
    }
    {
      FieldsData fieldsDataParameter[] = FieldsData.selectUpdatables(pool, strTab);
      for (int i=0;i< fieldsDataParameter.length; i++) {
        fieldsDataParameter[i].name = Sqlc.TransformaNombreColumna(fieldsDataParameter[i].name);
      }
      xmlDocumentXsql.setData("structure4", fieldsDataParameter);
    }
    {
      //Insert
      FieldsData[] fieldsDataInsert = null;
      fieldsDataInsert=copyarray(fieldsDataSelectAux);
      for (int i=1;i< fieldsDataInsert.length; i++) {
        if (!fieldsDataInsert[i].name.equalsIgnoreCase("Created") && !fieldsDataInsert[i].name.equalsIgnoreCase("CreatedBy") && !fieldsDataInsert[i].name.equalsIgnoreCase("Updated") && !fieldsDataInsert[i].name.equalsIgnoreCase("UpdatedBy")) fieldsDataInsert[i].name = ", " + fieldsDataInsert[i].name;
        else fieldsDataInsert[i].name = "";
      }
      xmlDocumentXsql.setData("structure5", fieldsDataInsert);
    }
    {
      FieldsData[] fieldsDataValue = null;
      fieldsDataValue=copyarray(fieldsDataSelectAux);
      for (int i=0;i<fieldsDataValue.length; i++) {
        if (!fieldsDataValue[i].name.equalsIgnoreCase("Created") && !fieldsDataValue[i].name.equalsIgnoreCase("CreatedBy") && !fieldsDataValue[i].name.equalsIgnoreCase("Updated") && !fieldsDataValue[i].name.equalsIgnoreCase("UpdatedBy")) {
          if (WadUtility.isTimeField(fieldsDataValue[i].reference)) fieldsDataValue[i].name =   ((i>0)?", ":"") + "TO_DATE(?, 'HH24:MI:SS')";
          else fieldsDataValue[i].name =   ((i>0)?", ":"") + WadUtility.sqlCasting(pool, fieldsDataValue[i].reference, fieldsDataValue[i].referencevalue) + "(?)";
        } else fieldsDataValue[i].name = "";
      }
      xmlDocumentXsql.setData("structure6", fieldsDataValue);
    }
    {
      Vector<Object> vecAux = new Vector<Object>();
      FieldsData[] fieldsDataParameterInsert = null;
      fieldsDataParameterInsert=copyarray(fieldsDataSelectAux);
      for (int i=0;i< fieldsDataParameterInsert.length; i++) {
        if (!fieldsDataParameterInsert[i].name.equalsIgnoreCase("Created") && !fieldsDataParameterInsert[i].name.equalsIgnoreCase("CreatedBy") && !fieldsDataParameterInsert[i].name.equalsIgnoreCase("Updated") && !fieldsDataParameterInsert[i].name.equalsIgnoreCase("UpdatedBy")) {
          fieldsDataParameterInsert[i].name = Sqlc.TransformaNombreColumna(fieldsDataParameterInsert[i].name);
          vecAux.addElement(fieldsDataParameterInsert[i]);
        }
      }
      FieldsData[] fieldsDataParameterInsert1 = null;
      if (vecAux.size()>0) {
        fieldsDataParameterInsert1 = new FieldsData[vecAux.size()];
        vecAux.copyInto(fieldsDataParameterInsert1);
      }
      xmlDocumentXsql.setData("structure7", fieldsDataParameterInsert1);
    }
    {
      FieldsData fieldsDataDefaults[] = FieldsData.selectDefaultValue(pool, "", strTab);
      Vector<Object> vecDDef = new Vector<Object>();
      for (int i=0;i< fieldsDataDefaults.length; i++) {
        boolean modified = false;
        if (parentsFieldsData==null || parentsFieldsData.length==0 || !parentsFieldsData[0].name.equalsIgnoreCase(fieldsDataDefaults[i].columnname)) {
          fieldsDataDefaults[i].name = Sqlc.TransformaNombreColumna(fieldsDataDefaults[i].name);
          fieldsDataDefaults[i].columnname = Sqlc.TransformaNombreColumna(fieldsDataDefaults[i].columnname);
          vecDDef.addElement(fieldsDataDefaults[i]);
          modified=true;
        }
        if ((fieldsDataDefaults[i].referencevalue.equals("30") || fieldsDataDefaults[i].reference.equals("800011") || fieldsDataDefaults[i].referencevalue.equals("31") || fieldsDataDefaults[i].referencevalue.equals("32") || fieldsDataDefaults[i].referencevalue.equals("35") || fieldsDataDefaults[i].referencevalue.equals("21") || fieldsDataDefaults[i].referencevalue.equals("25")) && fieldsDataDefaults[i].isdisplayed.equals("Y")) {
          FieldsData f = new FieldsData();
          f.name = (modified?fieldsDataDefaults[i].name:Sqlc.TransformaNombreColumna(fieldsDataDefaults[i].name)) + "r";
          f.columnname = (modified?fieldsDataDefaults[i].columnname:Sqlc.TransformaNombreColumna(fieldsDataDefaults[i].columnname)) + "r";
          vecDDef.addElement(f);
        } else if (fieldsDataDefaults[i].referencevalue.equals("28") && fieldsDataDefaults[i].isdisplayed.equals("Y") && !fieldsDataDefaults[i].type.equals("")) {
          FieldsData f = new FieldsData();
          f.name = (modified?fieldsDataDefaults[i].name:Sqlc.TransformaNombreColumna(fieldsDataDefaults[i].name)) + "Btn";
          f.columnname = (modified?fieldsDataDefaults[i].columnname:Sqlc.TransformaNombreColumna(fieldsDataDefaults[i].columnname)) + "Btn";
          vecDDef.addElement(f);
        }
      }
      FieldsData[] f1 = new FieldsData[vecDDef.size()];
      vecDDef.copyInto(f1);
      xmlDocumentXsql.setData("structure8", f1);
    }

    {
      ActionButtonRelationData[] abrd = WadActionButton.buildActionButtonSQL(pool, strTab);
      xmlDocumentXsql.setData("structure11", abrd);
    }

    {
      FieldsData[] encryptedData = FieldsData.selectEncrypted(pool, strTab);
      if (encryptedData!=null && encryptedData.length>0) {
        for (int g=0;g<encryptedData.length;g++) {
          encryptedData[g].realname = Sqlc.TransformaNombreColumna(encryptedData[g].realname);
          encryptedData[g].name = FormatUtilities.replace(encryptedData[g].name);
        }
      }
      xmlDocumentXsql.setData("structure17", encryptedData);
    }

    xmlDocumentXsql.setData("structure13", selCol);

    WadUtility.writeFile(fileDir, tabName + "_data.xsql", "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" + xmlDocumentXsql.print());
  }


  private void processTabComboReloads(File fileDir, String strTab, FieldsData[] parentsFieldsData, Vector<Object> vecFields, String isSOTrx) throws ServletException, IOException {
    log4j.debug("Procesig combo reloads java for tab: " + strTab);
    FieldsData[] data = FieldsData.selectValidationTab(pool, strTab);
    if (data==null || data.length==0) return;
    XmlDocument xmlDocument = xmlEngine.readXmlTemplate("org/openbravo/wad/ComboReloads").createXmlDocument();
    xmlDocument.setParameter("tabId", strTab);
    Vector<Object> vecReloads = new Vector<Object>();
    Vector<Object> vecTotal = new Vector<Object>();
    FieldsData[] result = null;
    for (int i=0;i<data.length;i++) {
      String code = data[i].whereclause + ((!data[i].whereclause.equals("") && !data[i].referencevalue.equals(""))?" AND ":"") + data[i].referencevalue;
      data[i].columnname = "inp" + Sqlc.TransformaNombreColumna(data[i].columnname);
      data[i].whereclause=WadUtility.getComboReloadText(code, vecFields, parentsFieldsData, vecReloads, "inp");
      if (!data[i].whereclause.equals("") && data[i].isdisplayed.equals("Y") && (data[i].reference.equals("17") || data[i].reference.equals("18") || data[i].reference.equals("19"))) {
        if (data[i].reference.equals("17")) { //List
          data[i].tablename = "List";
          data[i].tablenametrl = "List";
          data[i].htmltext = "select";
          data[i].htmltexttrl = "selectLanguage";
          data[i].xmltext = ", \"" + data[i].nameref + "\"";
          data[i].xmltexttrl = data[i].xmltext + ", vars.getLanguage()";
          data[i].xmltext += ", \"\"";
          data[i].xmltexttrl += ", \"\"";
        } else if (data[i].reference.equals("18")) { //Table
          FieldsData[] tables = FieldsData.selectColumnTable(pool, strTab, data[i].id);
          if (tables==null || tables.length==0) throw new ServletException("No se ha encontrado la Table para la columnId: " + data[i].id);
          StringBuffer where = new StringBuffer();
          Vector<Object> vecFields1 = new Vector<Object>();
          Vector<Object> vecTables = new Vector<Object>();
          Vector<Object> vecWhere = new Vector<Object>();
          Vector<Object> vecParameters = new Vector<Object>();
          Vector<Object> vecTableParameters = new Vector<Object>();
          String translated = WadUtility.columnIdentifier(pool, tables[0].tablename, true, tables[0], 0, 0, true, vecFields1, vecTables, vecWhere, vecParameters, vecTableParameters, sqlDateFormat);
          where.append(tables[0].whereclause);
          data[i].tablename = "TableList";
          data[i].htmltext = "select" + tables[0].referencevalue;
          if (!tables[0].columnname.equals("")) {
            data[i].htmltext += "_" + tables[0].columnname;
            data[i].tablename = "TableListVal";
            if (!where.toString().equals("")) where.append(" AND ");
            where.append(tables[0].defaultvalue);
          }
          data[i].tablenametrl = data[i].tablename + "Trl";
          data[i].htmltexttrl = data[i].htmltext;
          data[i].xmltext = "";
          if (vecTableParameters.size()>0) {
            data[i].xmltext = ", vars.getLanguage()";
          }
          data[i].xmltext+=", Utility.getContext(this, vars, \"#User_Org\", windowId), Utility.getContext(this, vars, \"#User_Client\", windowId)";
          data[i].xmltext += WadUtility.getWadComboReloadContext(where.toString(), isSOTrx);
          data[i].xmltexttrl = data[i].xmltext;
          if (vecParameters.size()>0 && vecTableParameters.size()==0) {
            data[i].xmltext += ", vars.getLanguage()";
            data[i].xmltexttrl += ", vars.getLanguage()";
          }
          data[i].xmltext += ", \"\"";
          data[i].xmltexttrl += ", \"\"";
        } else if (data[i].reference.equals("19")) { //TableDir
          FieldsData[] tableDir = FieldsData.selectColumnTableDir(pool, strTab, data[i].id);
          if (tableDir==null || tableDir.length==0) throw new ServletException("No se ha encontrado la TableDir para la columnId: " + data[i].id);
          data[i].tablename = "TableDir";
          data[i].htmltext = "select" + tableDir[0].referencevalue;
          String table_Name = tableDir[0].name.substring(0,tableDir[0].name.length()-3);
          Vector<Object> vecFields1 = new Vector<Object>();
          Vector<Object> vecTables = new Vector<Object>();
          Vector<Object> vecWhere = new Vector<Object>();
          Vector<Object> vecParameters = new Vector<Object>();
          Vector<Object> vecTableParameters = new Vector<Object>();
          String translated = WadUtility.columnIdentifier(pool, table_Name, true, tableDir[0], 0, 0, true, vecFields1, vecTables, vecWhere, vecParameters, vecTableParameters, sqlDateFormat);
          data[i].xmltext = "";
          if (vecTableParameters.size()>0) {
            data[i].xmltext = ", vars.getLanguage()";
          }
          data[i].xmltext += ", Utility.getContext(this, vars, \"#User_Org\", windowId), Utility.getContext(this, vars, \"#User_Client\", windowId)";
          if (!tableDir[0].columnname.equals("")) {
            data[i].htmltext += "_" + tableDir[0].columnname;
            data[i].tablename = "TableDirVal";
            data[i].xmltext += WadUtility.getWadComboReloadContext(tableDir[0].defaultvalue, isSOTrx);
          } else {
            data[i].tablename = "TableDir";
          }
          data[i].tablenametrl = data[i].tablename + "Trl";
          data[i].htmltexttrl = data[i].htmltext;
          data[i].xmltexttrl = data[i].xmltext;
          if (vecParameters.size()>0 && vecTableParameters.size()==0) {
            data[i].xmltext += ", vars.getLanguage()";
            data[i].xmltexttrl += ", vars.getLanguage()";
          }
          data[i].xmltext += ", \"\"";
          data[i].xmltexttrl += ", \"\"";
        }
        vecTotal.addElement(data[i]);
      }
    }
    if (vecTotal!=null && vecTotal.size()>0) {
      result = new FieldsData[vecTotal.size()];
      vecTotal.copyInto(result);
    }

    xmlDocument.setData("structure1", result);
    if (vecTotal==null || vecTotal.size()==0) return;
    WadUtility.writeFile(fileDir, "ComboReloads" + strTab + ".java", xmlDocument.print());
  }


  private void processTabXmlSortTab(FieldsData[] parentsFieldsData, File fileDir, String strTab, String tabName, String keyColumnName) throws ServletException, IOException {
    log4j.debug("Procesig relation sort tab xml: " + strTab + ", " + tabName);
    String[] discard = {""};
    if (parentsFieldsData==null || parentsFieldsData.length == 0) discard[0] = new String("sectionParent");
    XmlDocument xmlDocumentRXml = xmlEngine.readXmlTemplate("org/openbravo/wad/ConfigurationSortTab_Relation", discard).createXmlDocument();
    xmlDocumentRXml.setParameter("class", tabName + "_Relation.html");
    xmlDocumentRXml.setParameter("key", keyColumnName);
    if (parentsFieldsData!=null && parentsFieldsData.length > 0) {
      xmlDocumentRXml.setParameter("parent", parentsFieldsData[0].name);
    }
    WadUtility.writeFile(fileDir, tabName + "_Relation.xml", "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" + xmlDocumentRXml.print());
  }

  private void processTabHtmlSortTab(FieldsData[] parentsFieldsData, File fileDir, String strTab, String tabName, String windowName, String keyColumnName, String tabNamePresentation, TabsData[] allTabs, String strProcess, String strDirectPrint, String strParentNameDescription, String WindowPathName, String strLanguage) throws ServletException, IOException {
    log4j.debug("Procesig relation sort tab html: " + strTab + ", " + tabName);
    XmlDocument xmlDocumentRHtml;
    String[] discard = new String[3];
    if (strProcess.equals("")) {
      discard[0] = new String("printButton");
    } else {
      discard[0] = new String("");
    }
    if (allTabs.length<=NUM_TABS) discard[1] = new String("tabButton");
    else discard[1] = new String("");
    if (parentsFieldsData.length == 0) discard[2] = new String("parent");
    else discard[2] = new String("");

    xmlDocumentRHtml = xmlEngine.readXmlTemplate("org/openbravo/wad/TemplateSortTab_Relation", discard).createXmlDocument();
    xmlDocumentRHtml.setParameter("tab", tabNamePresentation);
    xmlDocumentRHtml.setParameter("form", tabName + "_Relation.html");
    xmlDocumentRHtml.setParameter("key", "inp" + Sqlc.TransformaNombreColumna(keyColumnName));
    xmlDocumentRHtml.setParameter("tabId", strTab);
    if (parentsFieldsData.length > 0) {
      xmlDocumentRHtml.setParameter("keyParent", "inp" + Sqlc.TransformaNombreColumna(parentsFieldsData[0].name));
      xmlDocumentRHtml.setParameter("parentKeyNameDescription", strParentNameDescription);
      xmlDocumentRHtml.setParameter("parentKeyName", parentsFieldsData[0].name);
    }
    
    xmlDocumentRHtml.setParameter("subtabKey", tabName);
    WadUtility.writeFile(fileDir, tabName + "_Relation.html", xmlDocumentRHtml.print());
  }


  private void processTabXmlRelation(FieldsData[] parentsFieldsData, File fileDir, String strTab, String tabName, String keyColumnName, WADControl relationControl) throws ServletException, IOException {
    log4j.debug("Procesig relation xml: " + strTab + ", " + tabName);
    String[] discard = {""};
    if (parentsFieldsData==null || parentsFieldsData.length == 0) discard[0] = new String("sectionParent");
    XmlDocument xmlDocumentRXml = xmlEngine.readXmlTemplate("org/openbravo/wad/Configuration_Relation", discard).createXmlDocument();
    xmlDocumentRXml.setParameter("class", tabName + "_Relation.html");
    xmlDocumentRXml.setParameter("key", keyColumnName);
    if (parentsFieldsData!=null && parentsFieldsData.length > 0) {
      xmlDocumentRXml.setParameter("parent", parentsFieldsData[0].name);
    }
    xmlDocumentRXml.setParameter("relationControl", relationControl.toXml());
    WadUtility.writeFile(fileDir, tabName + "_Relation.xml", "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" + xmlDocumentRXml.print());
  }

  private void processTabHtmlRelation(FieldsData[] parentsFieldsData, File fileDir, String strTab, String tabName, String keyColumnName, boolean isreadonly, String strParentNameDescription, WADControl control, boolean isTranslated, String adLanguage, String tabNamePresentation, String strTable) throws ServletException, IOException {
    log4j.debug("Procesig relation html" + (isTranslated?" translated":"") + ": " + strTab + ", " + tabName);
    String[] discard = new String[1];
    if (parentsFieldsData.length == 0) discard[0] = new String("parent");
    else discard[0] = new String("");

    XmlDocument xmlDocument = xmlEngine.readXmlTemplate("org/openbravo/wad/Template_Relation", discard).createXmlDocument();
    xmlDocument.setParameter("form", tabName + "_Edition.html");
    xmlDocument.setParameter("tab", tabNamePresentation);
    xmlDocument.setParameter("key", "inp" + Sqlc.TransformaNombreColumna(keyColumnName));
    xmlDocument.setParameter("keyId", keyColumnName);
    xmlDocument.setParameter("tabId", strTab);
    xmlDocument.setParameter("tableId", strTable);
    if (parentsFieldsData.length > 0) {
      xmlDocument.setParameter("keyParent", "inp" + Sqlc.TransformaNombreColumna(parentsFieldsData[0].name));
      xmlDocument.setParameter("parentKeyNameDescription", strParentNameDescription);
      xmlDocument.setParameter("parentKeyName", parentsFieldsData[0].name);
    }
    xmlDocument.setParameter("importCSS", getVectorElementsNotRepeated(control.getCSSImport(), new Vector<String>(), 1));
    xmlDocument.setParameter("importJS", getVectorElementsNotRepeated(control.getImport(), new Vector<String>(), 2));
    StringBuffer script = new StringBuffer();
    script.append(getVectorElementsNotRepeated(control.getJSCode(), new Vector<String>(), 0));
    script.append("function depurarClient(action, Formulario, valor) {\n");
    script.append("  var frm=document.frmMain;\n");
    script.append(control.getValidation()).append("\n");
    script.append("  return true;\n");
    script.append("}\n");
    xmlDocument.setParameter("script", script.toString());
    xmlDocument.setParameter("controlDesign", control.toString());
    WadUtility.writeFile(fileDir, tabName + "_Relation.html", xmlDocument.print());
  }

  private String getVectorElementsNotRepeated(Vector<String[]> data, Vector<String> addedElements, int type) {
    if (addedElements==null) addedElements = new Vector<String>();
    if (data==null) return "";
    StringBuffer text = new StringBuffer();
    for (int i=0;i<data.size();i++) {
      String[] aux = data.elementAt(i);
      if (!isInVector(addedElements, aux[0])) {
        addedElements.addElement(aux[0]);
        if (type==1) text.append("<link rel=\"stylesheet\" type=\"text/css\" href=\"");
        else if (type==2) text.append("<script language=\"JavaScript\" src=\"");
        text.append(aux[1]);
        if (type==1) text.append("\"/>");
        else if (type==2)text.append("\" type=\"text/javascript\"></script>");
        text.append("\n");
      }
    }
    return text.toString();
  }

  private boolean isInVector(Vector<String> data, String value) {
    if (data==null) return false;
    if (value==null || value.equals("")) return false;
    for (int i=0;i<data.size();i++) {
      String aux = data.elementAt(i);
      if (aux.equalsIgnoreCase(value)) return true;
    }
    return false;
  }

  private void processTabXmlEdition(File fileDir, String strTab, String tabName, String windowId, boolean isreadonly, FieldProvider[] efd, FieldProvider[] efdauxiliar) throws ServletException, IOException {
    if (log4j.isDebugEnabled()) log4j.debug("Processing edition xml: " + strTab + ", " + tabName);
    XmlDocument xmlDocument = xmlEngine.readXmlTemplate("org/openbravo/wad/Configuration_Edition").createXmlDocument();
    xmlDocument.setParameter("class", tabName + "_Edition.html");
    StringBuffer htmlHidden = new StringBuffer();
    if (efdauxiliar!=null) {
      for (int i=0;i< efdauxiliar.length; i++) {
        WADControl auxControl = new WADHidden(efdauxiliar[i].getField("columnname"), Sqlc.TransformaNombreColumna(efdauxiliar[i].getField("columnname")), "", true);
        auxControl.setReportEngine(xmlEngine);
        htmlHidden.append(auxControl.toXml()).append("\n");
      }
    }
    xmlDocument.setParameter("hiddens", htmlHidden.toString());

    StringBuffer html = new StringBuffer();
    for (int i=0;i< efd.length; i++) {
      WADControl auxControl = null;
      try {
        auxControl = WadUtility.getControl(pool, efd[i], isreadonly, tabName, "", xmlEngine, false, false);
      } catch (Exception ex) {
        throw new ServletException(ex);
      }
      html.append(auxControl.toXml()).append("\n");
    }

    xmlDocument.setParameter("fields", html.toString());
    WadUtility.writeFile(fileDir, tabName + "_Edition.xml", "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" + xmlDocument.print());
  }

  private void processTabHtmlEdition(FieldProvider[] efd, FieldProvider[] efdauxiliar, File fileDir, String strTab, String tabName, String keyColumnName, String tabNamePresentation, String windowId, FieldsData[] parentsFieldsData, Vector<Object> vecFields, boolean isreadonly, String isSOTrx, String strTable, double pixelSize, String strLanguage) throws ServletException, IOException {
    if (log4j.isDebugEnabled()) log4j.debug("Procesig edition html" + (strLanguage.equals("")?"":" translated") + ": " + strTab + ", " + tabName);
    XmlDocument xmlDocument = xmlEngine.readXmlTemplate("org/openbravo/wad/Template_Edition").createXmlDocument();
    xmlDocument.setParameter("tab", tabNamePresentation);
    xmlDocument.setParameter("form", tabName+ "_Relation.html");
    xmlDocument.setParameter("key", "inp" + Sqlc.TransformaNombreColumna(keyColumnName));
    xmlDocument.setParameter("keyId", keyColumnName);
    xmlDocument.setParameter("tabId", strTab);
    xmlDocument.setParameter("tableId", strTable);
    Vector<Object> vecDisplayLogic = new Vector<Object>();
    EditionFieldsData efdDl[] = EditionFieldsData.selectDisplayLogic(pool, strTab);
    if (efdDl!=null) {
      for (int i=0;i< efdDl.length; i++) {
        WadUtility.displayLogic(efdDl[i].displaylogic, vecDisplayLogic, parentsFieldsData, new Vector<Object>(), vecFields, windowId, new Vector<Object>());
      }
    }
    Vector<Object> vecAuxiliar = new Vector<Object>();
    StringBuffer htmlHidden = new StringBuffer();
    if (efdauxiliar!=null) {
      for (int i=0;i< efdauxiliar.length; i++) {
        WADControl auxControl = new WADHidden(efdauxiliar[i].getField("columnname"), Sqlc.TransformaNombreColumna(efdauxiliar[i].getField("columnname")), "", true);
        auxControl.setReportEngine(xmlEngine);
        htmlHidden.append(auxControl.toString()).append("\n");
        vecAuxiliar.addElement(FormatUtilities.replace(efdauxiliar[i].getField("columnname")));
      }
    }

    FieldsData[] dataReload = FieldsData.selectValidationTab(pool, strTab);
    Vector<Object> vecReloads = new Vector<Object>();
    if (dataReload!=null && dataReload.length>0) {
      for (int z=0;z<dataReload.length;z++) {
        String code = dataReload[z].whereclause + ((!dataReload[z].whereclause.equals("") && !dataReload[z].referencevalue.equals(""))?" AND ":"") + dataReload[z].referencevalue;
        WadUtility.getComboReloadText(code, vecFields, parentsFieldsData, vecReloads, "", dataReload[z].columnname);
      }
    }

    Properties importsCSS = new Properties();
    Properties importsJS = new Properties();
    Properties javaScriptFunctions = new Properties();
    StringBuffer displayLogicFunction = new StringBuffer();
    StringBuffer validations = new StringBuffer();
    StringBuffer onload = new StringBuffer();
    StringBuffer html = new StringBuffer();
    String strFieldGroup = "";
    int columnType = 0;
    html.append("<tr>\n");
    html.append("  <td class=\"TableEdition_OneCell_width\"></td>\n");
    html.append("  <td class=\"TableEdition_TwoCells_width\"></td>\n");
    html.append("  <td class=\"TableEdition_OneCell_width\"></td>\n");
    html.append("  <td class=\"TableEdition_TwoCells_width\"></td>\n");
    html.append("</tr>\n");
    for (int i=0;i< efd.length; i++) {
      WADControl auxControl = null;
      try {
        auxControl = WadUtility.getControl(pool, efd[i], isreadonly, tabName, strLanguage, xmlEngine, (WadUtility.isInVector(vecDisplayLogic, efd[i].getField("columnname"))), WadUtility.isInVector(vecReloads, efd[i].getField("columnname")));
      } catch (Exception ex) {
        throw new ServletException(ex);
      }
      if (WadUtility.isNewGroup(auxControl, strFieldGroup)) {
        strFieldGroup = auxControl.getData("AD_FieldGroup_ID");
        html.append("      <tr><td colspan=\"4\">\n");
        html.append("      <table border=0 cellspacing=0 cellpadding=0 class=\"FieldGroup\"><tr class=\"FieldGroup_TopMargin\"></tr>\n<tr>\n");
        html.append("<td class=\"FieldGroupTitle_Left\"><img src=\"../../../../../web/images/blank.gif\" class=\"FieldGroupTitle_Left_bg\" border=0/></td>");
        String strText="";
        if (strLanguage.equals("")) strText = EditionFieldsData.fieldGroupName(pool, strFieldGroup);
        else strText = EditionFieldsData.fieldGroupNameTrl(pool, strLanguage, strFieldGroup);
        String total=Double.toString((strText.length()+1) * pixelSize);
        html.append("<td class=\"FieldGroupTitle\">").append(strText).append("</td>");
        html.append("<td class=\"FieldGroupTitle_Right\"><img src=\"../../../../../web/images/blank.gif\" class=\"FieldGroupTitle_Right_bg\" border=0/></td>");
        html.append("<td class=\"FieldGroupContent\">&nbsp;</td></tr>\n<tr class=\"FieldGroup_BottomMargin\"></tr></table>");
        html.append("      </td></tr>\n");
      }

      if (log4j.isDebugEnabled()) log4j.debug("Column: " + auxControl.getData("ColumnName") + ", col:  " + columnType);
      // hidden inputs
      if (auxControl.getData("IsDisplayed").equals("N")) {
        htmlHidden.append(auxControl.toString()).append("\n");
      } else {
        if (auxControl.getData("IsSameLine").equals("Y")) {
          columnType = COLUMN_2_OF_2;
          html.append("<td");
        } else if (i < efd.length -1 && efd[i+1].getField("issameline").equals("Y") && efd[i+1].getField("isdisplayed").equals("Y")) {
          columnType = COLUMN_1_OF_2;
          html.append("<tr><td");
        } else {
          columnType = COLUMN_1_OF_1;
          html.append("<tr><td");
        }
        WadUtility.setLabel(pool, auxControl, isSOTrx.equals("Y"), "inp" + Sqlc.TransformaNombreColumna(keyColumnName));
        String label = auxControl.toLabel();
        if (!label.equals("")) {
          html.append(" class=\"TitleCell\" id=\"").append(auxControl.getData("ColumnName")).append("_lbl_td\">").append(label.replace("\n", ""));
          if (columnType == COLUMN_1_OF_1) html.append("</td>\n<td colspan=\"3\" class=\"").append(auxControl.getType()).append("_ContentCell\" id=\"").append(auxControl.getData("ColumnName")).append("_inp_td\">");
          else html.append("</td>\n<td class=\"").append(auxControl.getType()).append("_ContentCell\" id=\"").append(auxControl.getData("ColumnName")).append("_inp_td\">");
        } else {
          html.append(" class=\"").append(auxControl.getType()).append("_ContentCell\" id=\"").append(auxControl.getData("ColumnName")).append("_inp_td\"");
          if (columnType == COLUMN_1_OF_1) html.append(" colspan=\"4\">");
          else html.append(" colspan=\"2\">");
        }

        boolean isCombo = (auxControl.getData("AD_Reference_ID").equals("17") || auxControl.getData("AD_Reference_ID").equals("18") || auxControl.getData("AD_Reference_ID").equals("19"));
        if (columnType==COLUMN_1_OF_1) {
          if (Integer.valueOf(auxControl.getData("DisplayLength")).intValue() < (MAX_SIZE_EDITION_1_COLUMNS/4)) {
            auxControl.setData("DisplayLength", Double.toString(MAX_SIZE_EDITION_1_COLUMNS * (isCombo?7.5:1)));
            auxControl.setData("CssSize", "OneCell");
          } else if (Integer.valueOf(auxControl.getData("DisplayLength")).intValue() > (MAX_SIZE_EDITION_1_COLUMNS/2)) {
            auxControl.setData("DisplayLength", Double.toString(MAX_SIZE_EDITION_1_COLUMNS * (isCombo?7.5:1)));
            auxControl.setData("CssSize", "FiveCells");
          } else {
            auxControl.setData("DisplayLength", Double.toString((MAX_SIZE_EDITION_1_COLUMNS/2) * (isCombo?7.5:1)));
            auxControl.setData("CssSize", "TwoCells");
          }
        } else {
          if (Integer.valueOf(auxControl.getData("DisplayLength")).intValue() > (MAX_SIZE_EDITION_2_COLUMNS/2)) {
            auxControl.setData("DisplayLength", Double.toString(MAX_SIZE_EDITION_2_COLUMNS * (isCombo?7.5:1)));
            auxControl.setData("CssSize", "TwoCells");
          } else {
            auxControl.setData("DisplayLength", Double.toString((MAX_SIZE_EDITION_2_COLUMNS/2) * (isCombo?7.5:1)));
            auxControl.setData("CssSize", "OneCell");
          }
        }
        html.append(auxControl.toString());
        // end of input tag
        html.append("</td>\n");
        if (columnType == COLUMN_1_OF_1 || columnType == COLUMN_2_OF_2) html.append("</tr>\n");
        //Getting JavaScript
        {
          Vector<String[]> auxJavaScript = auxControl.getJSCode();
          if (auxJavaScript!=null) {
            for (int j=0;j<auxJavaScript.size();j++) {
              String[] auxObj = auxJavaScript.elementAt(j);
              javaScriptFunctions.setProperty(auxObj[0], auxObj[1]);
            }
          }
        } //End getting JavaScript
        //Getting css imports
        {
          Vector<String[]> auxCss = auxControl.getCSSImport();
          if (auxCss!=null) {
            for (int j=0;j<auxCss.size();j++) {
              String[] auxObj = auxCss.elementAt(j);
              importsCSS.setProperty(auxObj[0], auxObj[1]);
            }
          }
        } //End getting css imports
        //Getting js imports
        {
          Vector<String[]> auxJs = auxControl.getImport();
          if (auxJs!=null) {
            for (int j=0;j<auxJs.size();j++) {
              String[] auxObj = auxJs.elementAt(j);
              importsJS.setProperty(auxObj[0], auxObj[1]);
            }
          }
        } //End getting js imports
        if (!auxControl.getValidation().equals("")) validations.append(auxControl.getValidation()).append("\n");
        if (!auxControl.getOnLoad().equals("")) onload.append(auxControl.getOnLoad()).append("\n");
        displayLogicFunction.append(WadUtility.getDisplayLogic(auxControl, new Vector<Object>(), parentsFieldsData, vecAuxiliar, vecFields, windowId, new Vector<Object>(), isreadonly));
      }
    }

    xmlDocument.setParameter("hiddenControlDesign", htmlHidden.toString());
    xmlDocument.setParameter("controlDesign", html.toString());
    StringBuffer sbImportCSS = new StringBuffer();
    for (Enumeration e = importsCSS.propertyNames();e.hasMoreElements();) {
      String _name = (String)e.nextElement();
      sbImportCSS.append("<link rel=\"stylesheet\" type=\"text/css\" href=\"").append(importsCSS.getProperty(_name)).append("\"/>\n");
    }
    xmlDocument.setParameter("importCSS", sbImportCSS.toString());
    StringBuffer sbImportJS = new StringBuffer();
    boolean hasCalendar = false;
    boolean calendarInserted = false;
    boolean calendarLangInserted = false;
    for (Enumeration e = importsJS.propertyNames();e.hasMoreElements();) {
      String _name = (String)e.nextElement();
      if (_name.startsWith("calendar")) hasCalendar = true;
      if (!_name.equals("calendarLang") || calendarInserted) {
        sbImportJS.append("<script language=\"JavaScript\" src=\"").append(importsJS.getProperty(_name)).append("\" type=\"text/javascript\"></script>\n");
        if (_name.equals("calendarLang")) calendarLangInserted = true;
      }
      if (_name.equals("calendar")) calendarInserted = true;
    }
    if (hasCalendar && !calendarLangInserted) sbImportJS.append("<script language=\"JavaScript\" src=\"").append(importsJS.getProperty("calendarLang")).append("\" type=\"text/javascript\"></script>\n");
    xmlDocument.setParameter("importJS", sbImportJS.toString());
    StringBuffer script = new StringBuffer();
    for (Enumeration e = javaScriptFunctions.propertyNames();e.hasMoreElements();) {
      String _name = (String)e.nextElement();
      script.append(javaScriptFunctions.getProperty(_name)).append("\n");
    }
    script.append("\nfunction reloadComboReloads").append(strTab).append("(changedField) {\n");
    script.append("  submitCommandForm(changedField, false, null, '../ad_callouts/ComboReloads' + document.frmMain.inpTabId.value + '.html', 'frameOculto', null, null, true);\n");
    script.append("  return true;\n");
    script.append("}\n");
    script.append("\nfunction depurarClient(action, Formulario, valor) {\n");
    script.append("  var frm=document.frmMain;\n");
    script.append(validations);
    script.append("  return true;\n");
    script.append("}\n");

    script.append("\nfunction displayLogic() {\n");
    script.append(displayLogicFunction);
    script.append("  return true;\n");
    script.append("}\n");

    script.append("\nfunction onloadClient() {\n");
    script.append("  var frm=document.frmMain;\n");
    script.append("  var key = eval(\"document.frmMain.\" + frm.inpKeyName.value);");
    script.append(onload);
    script.append("  displayLogic();\n");
//    script.append("  setInputValue(frm.inpLastFieldChanged, \"\");\n");
    script.append("  return true;\n");
    script.append("}\n");

    xmlDocument.setParameter("script", script.toString());
    WadUtility.writeFile(fileDir, tabName + "_Edition.html", xmlDocument.print());
  }

/*#############################################################################################################################
#                                       Utilities                                                                             #
###############################################################################################################################*/
  private void getSubTabs (Vector<Object> vec, String strTabParent, String strTabSelected, String strLanguage) throws IOException, ServletException {
    TabsData[] aux = null;
    if (strLanguage==null || strLanguage.equals("")) aux = TabsData.selectSubtabs(pool, strTabParent);
    else aux = TabsData.selectSubtabsTrl(pool, strLanguage, strTabParent);
    if (aux==null || aux.length<=0) return;
    for (int i=0;i<aux.length;i++) {
      vec.addElement(aux[i]);
      getSubTabs(vec, aux[i].tabid, strTabSelected, strLanguage);
    }
  }

  private TabsData[] getPrimaryTabs(String strWindowId, String strTabSelected, int level, int heightTabs, int incrTabs, String strLanguage) throws IOException, ServletException {
    TabsData[] aux=null;
    TabsData[] aux1=null;
    int mayor=0;
    Vector<Object> vec = new Vector<Object>();
    if (strLanguage!=null && !strLanguage.equals("")) aux1 = TabsData.selectTabParentTrl(pool, strLanguage, strWindowId);
    else aux1 = TabsData.selectTabParent(pool, strWindowId);
    if (aux1==null || aux1.length==0) return null;
    for (int i=0;i<aux1.length;i++) {
      vec.addElement(aux1[i]);
      getSubTabs(vec, aux1[i].tabid, strTabSelected, strLanguage);
    }
    aux = new TabsData[vec.size()];
    vec.copyInto(aux);
    for (int i=0;i<aux.length;i++) 
      if (mayor<Integer.valueOf(aux[i].tablevel).intValue()) mayor=Integer.valueOf(aux[i].tablevel).intValue();
    for (int i=0;i<aux.length;i++) debugTab(aux[i], strTabSelected, level, heightTabs, incrTabs, mayor);
    return aux;
  }

  private void debugTab(TabsData tab, String strTab, int level, int heightTabs, int incrTabs, int mayor) throws ServletException {
    String tabName = FormatUtilities.replace(tab.tabname);
    if (strTab.equals(tab.tabid)) {
      tab.tdClass="";
      tab.href = "return false;";
    } else {
      tab.tdClass="";
      tab.href = "submitCommandForm('DEFAULT', false, null, '" + tabName + "_Relation.html', 'frameAplicacion');return false;";
      if ((level+1)>=Integer.valueOf(tab.tablevel).intValue()) tab.href = "submitCommandForm('" + ((level>Integer.valueOf(tab.tablevel).intValue())?"DEFAULT":"TAB") + "', " + ((level>=Integer.valueOf(tab.tablevel).intValue())?"false":"true") + ", null, '" + tabName + "_Relation.html', 'frameAplicacion');return false;";
      else tab.href = "return false;";
    }
    int height = ((mayor-Integer.valueOf(tab.tablevel).intValue())*incrTabs + heightTabs);
    tab.tdHeight = Integer.toString(height);
  }

  private int parentTabId(TabsData[] allTabs, String tabId) throws ServletException, IOException {
    if (allTabs==null || allTabs.length==0) return -1;
    else if (tabId==null || tabId.equals("")) return -1;
    else if (tabId.equals(allTabs[0].tabid)) return -1;
    String parentTab="";
    for (int i=1;i<allTabs.length;i++) {
      if (allTabs[i].tabid.equals(tabId)) {
        parentTab = allTabs[i].parentKey;
        break;
      }
    }
    if (!parentTab.equals("-1")) {
      for (int i=0;i<allTabs.length;i++) {
        if (allTabs[i].tabid.equals(parentTab)) return i;
      }
    }
    return -1;
  }


  public void fieldsOfTableDir(String tableInit, String name, String required, Vector<Object> vecFields, Vector<Object> vecTables, Vector<Object> vecWhere) throws ServletException{
    int ilength = name.length();
    String tableName = name.substring(0,ilength-3);
    FieldsData fdi[] = FieldsData.identifierColumns(pool, tableName);
    vecTables.addElement("left join " + tableName + " on (" + tableInit + "." + name + " = " + tableName + "." + name + ")");
    for (int i=0;i< fdi.length; i++) {
      if (fdi[i].reference.equals("19")) fieldsOfTableDir(tableName, fdi[i].name, fdi[i].required, vecFields, vecTables, vecWhere);
      else vecFields.addElement(tableName + "." + fdi[i].name);
    }
  }

  public int fieldsOfSearch(String tableInit, String name, String FilterName, String required, Vector<Object> vecFields, Vector<Object> vecTables, Vector<Object> vecWhere, int itable, String reference, String referencevalue) throws ServletException{
    itable++;
    int tableNum = itable;
    EditionFieldsData[] dataSearchs = null;
    if (reference.equals("30") && !referencevalue.equals("")) dataSearchs = EditionFieldsData.selectSearchs(pool, "", referencevalue);
    String tableName = "";
    if (dataSearchs==null || dataSearchs.length==0) {
      int ilength = FilterName.length();
      if (reference.equals("25")) tableName = "C_ValidCombination";
      else if (reference.equals("31")) tableName = "M_Locator";
      else if (reference.equals("800011")) tableName = "M_Product";
      else tableName = FilterName.substring(0,ilength-3);
      if (reference.equals("25")) FilterName = "C_ValidCombination_ID";
      else if (reference.equals("31")) FilterName = "M_Locator_ID";
      else if (reference.equals("800011")) FilterName = "M_Product_ID";
    } else {
      tableName = dataSearchs[0].reference;
      FilterName = dataSearchs[0].columnname;
    }
    FieldsData fdi[] = FieldsData.identifierColumns(pool, tableName);
    StringBuffer fieldsAux = new StringBuffer();
    for (int i=0;i< fdi.length; i++) {
      if (!fdi[i].columnname.equalsIgnoreCase(FilterName)) fieldsAux.append(", ").append(fdi[i].columnname);
    }
    vecTables.addElement("left join (select " + FilterName + fieldsAux.toString() + " from " + tableName + ") table" + tableNum + " on (" + tableInit + "." + name + " = table" + tableNum + "." + FilterName + ")");
    for (int i=0;i< fdi.length; i++) {
      if (fdi[i].reference.equals("30") || fdi[i].reference.equals("31") || fdi[i].reference.equals("35") || fdi[i].reference.equals("25") || fdi[i].reference.equals("800011") || fdi[i].reference.equals("19")) {
        itable=fieldsOfSearch("table" + tableNum, fdi[i].name, fdi[i].columnname, required, vecFields, vecTables, vecWhere, itable, fdi[i].reference, fdi[i].referencevalue);
      } else {
        vecFields.addElement("table" + tableNum + "." + fdi[i].columnname);
      }
    }
    return itable;
  }

  public int fieldsOfSearch2(String tableInit, String name, String required, Vector<Object> vecFields, Vector<Object> vecTables, Vector<Object> vecWhere, int itable, String reference, String referencevalue) throws ServletException{
    itable++;
    int tableNum = itable;
    String tableName = "";
    EditionFieldsData[] dataSearchs = null;
    if (reference.equals("30") && !referencevalue.equals("")) dataSearchs = EditionFieldsData.selectSearchs(pool, "", referencevalue);
    if (dataSearchs==null || dataSearchs.length==0) {
      int ilength = name.length();
      if (reference.equals("25")) tableName = "C_ValidCombination";
      else if (reference.equals("31")) tableName = "M_Locator";
      else if (reference.equals("800011")) tableName = "M_Product";
      else tableName = name.substring(0,ilength-3);
      if (reference.equals("25")) name = "C_ValidCombination_ID";
      else if (reference.equals("31")) name = "M_Locator_ID";
      else if (reference.equals("800011")) name="M_Product_ID";
      else name = name;
    } else {
      tableName = dataSearchs[0].reference;
      name = dataSearchs[0].columnname;
    }
    FieldsData fdi[] = FieldsData.identifierColumns(pool, tableName);
    if (itable>1) {
      vecTables.addElement(" left join " + tableName + " table" + tableNum + " on (" + tableInit + "." + name + " = table" + tableNum + "." + name + ")");
    }
    for (int i=0;i< fdi.length; i++) {
      if (fdi[i].reference.equals("30") || fdi[i].reference.equals("800011") || fdi[i].reference.equals("31") || fdi[i].reference.equals("35") || fdi[i].reference.equals("25")) {
        itable=fieldsOfSearch2("table" + tableNum, fdi[i].columnname, fdi[i].required, vecFields, vecTables, vecWhere, itable, fdi[i].reference, fdi[i].referencevalue);
      } else {
        vecFields.addElement("table" + tableNum + "." + fdi[i].columnname);
      }
    }
    return itable;
  }
/*
  public void connect() throws ClassNotFoundException, SQLException {
      log4j.info("Carga del driver: " + strDriver);
      Class.forName(strDriver);
      log4j.info("Driver cargado");
      log4j.info("Conexión con: "+ strURL);
      connection=DriverManager.getConnection(strURL);
      log4j.info("connect realizado");
  }

  public void closeConnection() {
    try {
      connection.close();
    } catch(SQLException e){
      log4j.error("Error de SQL en closeConnection: " + e);
    }
  }

  public void startElement(String name, Attributes amap) throws SAXException {
    log4j.debug("Configuration: startElement is called: element name=" + name);
    if (name.trim().equalsIgnoreCase("CONNECTION")) {
      for (int i = 0; i < amap.getLength(); i++) {     
        if (amap.getQName(i).equals("driver")) {
          strDriver = amap.getValue(i);
        } else if (amap.getQName(i).equals("URL")) {
          strURL = amap.getValue(i);
        }
      }
    }
  }
*/
  public void createXmlEngine(String fileConnection) {
    xmlEngine = new XmlEngine();
    xmlEngine.isResource = true;
    xmlEngine.fileBaseLocation = new File(".");
    xmlEngine.strReplaceWhat = null;
    xmlEngine.strReplaceWith = null;
    xmlEngine.strTextDividedByZero = "TextDividedByZero";
    xmlEngine.fileXmlEngineFormat = new File (fileConnection, "Format.xml");
    log4j.debug("xmlEngine format file: " + xmlEngine.fileXmlEngineFormat.getAbsoluteFile());
    xmlEngine.initialize();
  }

  public void createPool(String strFileConnection) {
    pool = new WadConnection(strFileConnection);
  }
  
  public FieldsData copyarrayElement(FieldsData from) {
    FieldsData toAux = new FieldsData();
    toAux.realname = from.realname;
    toAux.name = from.name;
    toAux.nameref = from.nameref;
    toAux.xmltext = from.xmltext;
    toAux.reference = from.reference;
    toAux.referencevalue = from.referencevalue;
    toAux.required = from.required;
    toAux.isdisplayed = from.isdisplayed;
    toAux.isupdateable = from.isupdateable;
    toAux.defaultvalue = from.defaultvalue;
    toAux.fieldlength = from.fieldlength;
    toAux.textAlign = from.textAlign;
    toAux.xmlFormat = from.xmlFormat;
    toAux.displaylength = from.displaylength;
    toAux.columnname = from.columnname;
    toAux.whereclause = from.whereclause;
    toAux.tablename = from.tablename;
    toAux.type = from.type;
    toAux.issessionattr = from.issessionattr;
    toAux.iskey = from.iskey;
    toAux.isparent = from.isparent;
    toAux.accesslevel = from.accesslevel;
    toAux.isreadonly = from.isreadonly;
    toAux.issecondarykey = from.issecondarykey;
    toAux.showinrelation = from.showinrelation;
    toAux.isencrypted = from.isencrypted;
    toAux.sortno = from.sortno;
    toAux.istranslated = from.istranslated;
    toAux.id = from.id;
    toAux.htmltext = from.htmltext;
    toAux.htmltexttrl = from.htmltexttrl;
    toAux.xmltexttrl = from.xmltexttrl;
    toAux.tablenametrl = from.tablenametrl;
    toAux.nowrap = from.nowrap;
    toAux.iscolumnencrypted = from.iscolumnencrypted;
    toAux.isdesencryptable = from.isdesencryptable;
    toAux.adReferenceValueId = from.adReferenceValueId;
    return toAux;
  }

  public FieldsData[] copyarray(FieldsData[] from) {
    log4j.debug("Starting copyarray: " + from.length);
    if (from==null) return null;
    FieldsData[] to = new FieldsData[from.length];
    for (int i=0;i<from.length;i++) {
      log4j.debug("For copyarray");
      to[i] = copyarrayElement(from[i]);
    }
    return to;
  }

  public void readProperties(String strFileProperties) {
//  Read properties file.
    Properties properties = new Properties();
    try {
        log4j.info("strFileProperties: " + strFileProperties);
        properties.load(new FileInputStream(strFileProperties));
        jsDateFormat = properties.getProperty("dateFormat.js");
        log4j.info("jsDateFormat: " + jsDateFormat);
        sqlDateFormat = properties.getProperty("dateFormat.sql");
        log4j.info("sqlDateFormat: " + sqlDateFormat);
    } catch (IOException e) { 
       // catch possible io errors from readLine()
       System.out.println("Uh oh, got an IOException error!");
       e.printStackTrace();
    }
  }

}
